如何手动将行添加到数据网格视图
问题描述:
我有一个显示在C#Windows窗体上的datagridview.
当用户插入一些记录时,我想同时向dgv添加新行.
请帮助我...
I have a datagridview that is displayed on the C# windows form.
I want to add new row simultanously to the dgv when user insert some record .
Please help me .....
private void btnInsert_Click(object sender, EventArgs e)
{
try
{
SqlConnection scon = new SqlConnection("Data Source=ASIC-02\\SQLEXPRESS;Initial Catalog=Student;Integrated Security=True");
scon.Open();
SqlCommand scom = new SqlCommand("rec",scon);
scom.CommandType = CommandType.StoredProcedure;
scom.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text;
scom.Parameters.Add("@Reg", SqlDbType.VarChar).Value = txtReg.Text;
scom.Parameters.Add("@Dep", SqlDbType.VarChar).Value = txtDep.Text;
dataGridView1.Rows.Add(txtName.Text, txtReg.Text, txtDep.Text);
scom.ExecuteNonQuery();
MessageBox.Show("Information Successfully Inserted");
scon.Close();
this.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
答
为此,您需要将行添加到使用的数据集中,然后重新渲染网格.
For this, you need to add the row to the dataset used and then re-render the grid.