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();
}