我是新的winform C#。现在,当我尝试向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);
}
}
这是我的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() + "' ");
我想在点击带有datagridview2
值的按钮时尝试添加newRow 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);
}
}
但if(!exists)
,这不起作用。
请帮帮我。
答案 0 :(得分:1)
而不是插入DataGridViewRow
尝试将DataRow
插入您的数据源
var dataSource = dataGridView1.DataSource as BindingSource;
var dataTable = dataSource.DataSource as DataTable;
dataTable.Rows.Add(value1, value2,...)
这将更新您的BindingSource
并显示DataTable的新值。