im using the following code to populate a Gridview.I add 2 buttons for editing and deleting at the end.Hook to the click event.. but after i add the delete
button the click events are not firing.What im i doing wrong?
private void BindGrid2()
{
try
{
string constr = "Data Source=INSPIRE-1;" +
"Initial Catalog=testdatabase;" +
"User id=testuser;" +
"Password=tester;";
using (SqlConnection con = new SqlConnection(constr))
{
string commandText = "SELECT invnumber,itemname,quantity,rate FROM mytable2 where invnumber= @name";
using (SqlCommand command = new SqlCommand(commandText, con))
{
command.Parameters.AddWithValue("@name", text_inv.Text);
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
}
}
if (flag2 == false)
{
flag2 = true;
DataGridViewButtonColumn uninstallButtonColumn = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Edit";
uninstallButtonColumn.Text = "Edit";
dataGridView2.Columns.Insert(0, uninstallButtonColumn);
dataGridView2.Columns[0].DisplayIndex = 4;
DataGridViewButtonColumn uninstallButtonColumn2 = new DataGridViewButtonColumn();
uninstallButtonColumn.Name = "Delete";
uninstallButtonColumn.Text = "Delete";
dataGridView2.Columns.Insert(5, uninstallButtonColumn2);
dataGridView2.Columns[5].DisplayIndex = 5;
}
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
var senderGrid = (DataGridView)sender;
string orderId;
if (e.ColumnIndex == 4)
{
try
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value;
using (SqlConnection conn = new SqlConnection(constr))
{
try
{
conn.Open();
SqlDataReader myReader = null;
string commandText = "select * from mytable2 where invnumber= @name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("@name", text_inv.Text);
myReader = command.ExecuteReader();
while (myReader.Read())
{
text_cname.Text = myReader["cname"].ToString();
text_quantity.Text = myReader["quantity"].ToString();
text_item.Text = myReader["itemname"].ToString();
text_rate.Text = myReader["rate"].ToString();
dateTimePicker1.Text = myReader["date"].ToString();
// textBox4.Text = myReader["stock"].ToString();
}
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
}
catch (Exception error)
{
}
}
else if (e.ColumnIndex == 5)
{
using (SqlConnection conn = new SqlConnection(constr))
{
orderId = (string)dataGridView1.SelectedCells[0].OwningRow.Cells[1].Value;
conn.Open();
SqlDataReader myReader = null;
string commandText = "delete from mytable2 where invnumber= @name";
SqlCommand command = new SqlCommand(commandText, conn);
command.Parameters.AddWithValue("@name", text_inv.Text);
myReader = command.ExecuteReader();
}
BindGrid2();
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…