所以我打算在双击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");
}
答案 0 :(得分:2)
1-你应该找到id而不是row index。您应该知道哪个列索引是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");
// ...
}
答案 1 :(得分:1)
首先,以下代码id = dataGridView1.CurrentCell.RowIndex;
闻起来,确保您确实获得了emplyeee Id值。
其次,WinForms数据绑定不支持" path" (如" Employee.LastName")作为WPF。为了实现目标,您需要绑定到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");
// ...
}