我设计了一个只有DataGridView
控件的 Windows 窗体应用程序。我以编程方式绑定数据库中的数据。我还编写了用于从DataGridView
单元格更新数据库记录的代码。但我不知道如何从这些将新记录插入数据库Cell
。你能帮我吗?
到目前为止,这是我的代码:
private void Form1_Load(object sender, EventArgs e)
{
try
{
con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
con.Open();
SqlCommand cmd = new SqlCommand("select * from student1", con);
da.SelectCommand = cmd;
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
da.Fill(ds, "student1");
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show("Exception caught : " + ex.Message.ToString());
}
finally
{
con.Close();
}
}
string s;
int x, y;
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
//s=dataGridView1.CurrentCell.ToString();
//x = dataGridView1.CurrentCellAddress.X;
//y = dataGridView1.CurrentCellAddress.Y;
}
private void dataGridView1_CancelRowEdit(object sender, QuestionEventArgs e)
{
x = -1;
y = -1;
}
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
x = dataGridView1.CurrentCellAddress.X;
y = dataGridView1.CurrentCellAddress.Y;
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
con.ConnectionString = "Data Source=CHANDU-PC;Initial Catalog=Class;Integrated Security=true;MultipleActiveResultSets=true;";
con.Open();
SqlCommand cmd;
if (e.ColumnIndex == 0)
{
cmd = new SqlCommand("Select * from student1", con);
da.SelectCommand = cmd;
cmd.ExecuteNonQuery();
MessageBox.Show("invalid column selected");
}
else
{
s = (string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
int i = -1;
i = (int)Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value);
if (e.ColumnIndex == 1)
cmd = new SqlCommand("update student1 set name='" + s + "' where id='" + i + "'", con);
else
cmd = new SqlCommand("update student1 set email='" + s + "' where id='" + i + "'", con);
da.UpdateCommand = cmd;
cmd.ExecuteNonQuery();
MessageBox.Show("Information updated Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Exception caught : " + ex.Message.ToString());
}
finally
{
con.Close();
}
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.Refresh();
}