【发布时间】:2015-10-16 17:34:02
【问题描述】:
所以我计划创建一个电话簿,当我双击 datagridview 中的数据/单元格时,将出现第二个表单(详细信息表单),它将显示该 ID 的所有其他详细信息,并且数据应该出现在文本框,但它不起作用。所以这是我的代码。谢谢!
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
int id;
id = dataGridView1.CurrentCell.RowIndex;
Details details = new Details(id);
details.Show();
}
详情页
public Details(int id)
{
InitializeComponent();
int val = id;
GetRecords(val);
}
private void GetRecords(int n)
{
SqlCommand cmd = new SqlCommand();
int id = n;
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Employee WHERE EmployeeID ='" + id + "';";
da = new SqlDataAdapter();
da.SelectCommand = cmd;
ds = new DataSet();
da.Fill(ds, "Employee");
}
private void AddDataBinding()
{
txtLN.DataBindings.Add("Text", ds, "Employee.LastName");
txtFN.DataBindings.Add("Text", ds, "Employee.FirstName");
txtMN.DataBindings.Add("Text", ds, "Employee.MiddleName");
txtAddress.DataBindings.Add("Text", ds, "Employee.Address");
txtAge.DataBindings.Add("Text", ds, "Employee.Age");
txtLN.DataBindings.Add("Text", ds, "Employee.LastName");
txtPhone.DataBindings.Add("Text", ds, "Employee.Phone");
txtMobile.DataBindings.Add("Text", ds, "Employee.Mobile");
txtEmail.DataBindings.Add("Text", ds, "Employee.Email");
dtBirthday.DataBindings.Add("Value", ds, "Employee.Birthday");
cbType.DataBindings.Add("SelectedItem", ds, "Employee.Type");
txtName.DataBindings.Add("Text", ds, "Employee.OtherName");
txtOPhone.DataBindings.Add("Text", ds, "Employee.OtherPhone");
txtOMobile.DataBindings.Add("Text", ds, "Employee.OtherMobile");
}
【问题讨论】:
-
你永远不会打电话给
AddDataBinding。更好地学习在 sql 查询中使用参数以避免 sql 注入。 -
- 在您的
CellContentDoubleClick中,您传递的是RowIndex而不是Id。 - 在您没有调用AddDataBinding的详细表单中- 考虑使用参数化查询。 - 考虑使用设计器来执行这样的数据绑定 -
传递所选员工 ID 的正确语法是什么?谢谢
-
@elowearth 如果您对答案有任何疑问,请告诉我。
标签: c# winforms visual-studio datagridview