winformc#中数据绑定错误
本文关键字:错误 数据绑定 winformc# | 更新日期: 2023-09-27 18:18:13
所以我计划创建一个电话簿,当我双击数据/单元格在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");
}
1-您应该找到id而不是行索引。您应该知道id对应哪个列索引,例如,如果id位于第一列,则可以使用以下命令:
var id = (int)dataGridView1.Rows[e.RowIndex].Cells[0].Value;
2-考虑使用这样的参数化查询:
cmd.CommandText = "SELECT * FROM Employee WHERE EmployeeID =@Id";
cmd.Parameters.AddWithValue("@Id", id);
//cmd.Parameters.Add("@Id", SqlDbType.Int).Value = id;
3-按照Ivan所说的方式执行数据绑定并调用AddDataBinding
DataTable dt;
private void GetRecords(int n)
{
//...
da.Fill(ds, "Employee");
dt = ds.Tables["Employee"];
AddDataBinding();
}
private void AddDataBinding()
{
txtLN.DataBindings.Add("Text", dt, "LastName");
txtFN.DataBindings.Add("Text", dt, "FirstName");
// ...
}
首先,下面的代码id = dataGridView1.CurrentCell.RowIndex;
闻到,确保您确实获得了员工Id值。
DataTable
,如下所示:
DataTable dt;
private void GetRecords(int n)
{
//...
da.Fill(ds, "Employee");
dt = ds.Tables["Employee"];
}
private void AddDataBinding()
{
txtLN.DataBindings.Add("Text", dt, "LastName");
txtFN.DataBindings.Add("Text", dt, "FirstName");
// ...
}