gpt4 book ai didi

c# - winform c# 中的数据绑定(bind)错误

转载 作者:太空宇宙 更新时间:2023-11-03 23:28:04 25 4
gpt4 key购买 nike

所以我计划创建一个电话簿,当我双击 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 的方式执行数据绑定(bind)说并调用 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");
// ...
}

关于c# - winform c# 中的数据绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33176329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com