I'm new winform C#.So now i have some problem when I trying add row to datagridview
public void SourceForDataGridView(string str)
{
try
{
SqlDataAdapter da = new SqlDataAdapter(str, cnn);
DataTable dt = new DataTable();
da.Fill(dt);
BindingSource bSource = new BindingSource();
bSource.DataSource = dt;
dataGridView1.DataSource = bSource;
da.Update(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
That's my source for datagridview1,
SourceForDataGridView("SELECT TenThuoc,DVTinh,SL,DONGIA,THANHTIEN,HSD FROM CTNHAPTHUOC JOIN THUOC ON CTNHAPTHUOC.MaThuoc = Thuoc.MaThuoc JOIN NHAPTHUOC ON NHAPTHUOC.MANHAPTHUOC = CTNHAPTHUOC.MANHAPTHUOC WHERE CTNHAPTHUOC.MaNhapThuoc = '" + txtMaPNT.Text.Trim() + "' ");
I want to try add newRow when click a button with value from datagridview2
double sum = 0;
sum = double.Parse(txtDGMua.Text.Trim().ToString()) * double.Parse(txtSLMua.Text.Trim().ToString());
bool existed = false;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int selectedrowindex = dataGridView2.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView2.Rows[selectedrowindex];
string a = Convert.ToString(selectedRow.Cells[0].Value);
string b = Convert.ToString(dataGridView1.Rows[i].Cells[0].Value);
if (a == b)
{
existed = true;
dataGridView1.Rows[i].Cells[2].Value = int.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString()) + int.Parse(txtSLMua.Text);
//sum += (double.Parse(txtDGMua.Text.Trim().ToString())*double.Parse(txtSLMua.Text.Trim().ToString()));
dataGridView1.Rows[i].Cells[4].Value = double.Parse(dataGridView1.Rows[i].Cells[2].Value.ToString()) * double.Parse(dataGridView1.Rows[i].Cells[3].Value.ToString());
break;
}
}
if (!existed)
{
try
{
//object[] item = { this.dataGridView2.CurrentRow.Cells[0].Value.ToString(), this.dataGridView2.CurrentRow.Cells[1].Value.ToString(), txtSLMua.Text, txtDGMua.Text, sum, dTPHSD.Value };
this.dataGridView1.Rows.Add(this.dataGridView2.CurrentRow.Cells[0].Value.ToString(), this.dataGridView2.CurrentRow.Cells[1].Value.ToString(), txtSLMua.Text, txtDGMua.Text, sum, dTPHSD.Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
but , if(!exists)
, this's not working.
Please help me.