【发布时间】:2016-01-18 07:14:50
【问题描述】:
我有以下用 WPF 表单编写的代码,并且运行良好。但后来我决定使用 XAML 来获得更好的 GUI 结果。此方法附加到 WPF 表单中的“CellClick”事件。它基本上负责获取选定的行,然后查询它以从数据库中获取数据。现在在 XAML 中没有称为“CellClick”的事件。什么是替代方法以及如何从 XAML 中的数据网格中获取选定的行。
private void employeeInfo_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
empId = Convert.ToInt32(employeeInfo.Rows[e.RowIndex].Cells["Employee ID"].Value.ToString());
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM Employees WHERE [Employee_id]=@employeeId";
cmd.Parameters.AddWithValue("@employeeId", empId);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
employeeIDTxt.Text = dr["Employee_Id"].ToString();
firstNameTxt.Text = dr["First_Name"].ToString();
lastNameTxt.Text = dr["Last_Name"].ToString();
addressTxt.Text = dr["Address"].ToString();
aptTxt.Text = dr["Apt"].ToString();
stateTxt.Text = dr["State"].ToString();
cityTxt.Text = dr["City"].ToString();
zipTxt.Text = dr["Zip"].ToString();
phoneTxt.Text = dr["Phone"].ToString();
cellTxt.Text = dr["Cell"].ToString();
emailTxt.Text = dr["Email"].ToString();
hourlyPayTxt.Text = dr["Hourly_Pay"].ToString();
passwordTxt.Text = dr["Password"].ToString();
statusTxt.Text = dr["Status"].ToString();
}
}
catch (ArgumentOutOfRangeException arg)
{
MessageBox.Show("Please select a vlaud Employee" +arg);
}
catch (Exception ex)
{
MessageBox.Show("WTF happened bro. check it again. Inside the Employee Info method" + ex);
}
}
我已尝试使用以下代码从所选行中获取特定列,但问题是此事件被触发两次,第二次引发argumentOutOfBound 异常。
private void employeeInfo_CellClick(object sender, System.Windows.Controls.SelectedCellsChangedEventArgs e)
{
MessageBox.Show("EmployeeInfo method");
DataRowView dg = (DataRowView)employeeInfo.SelectedItems[0];
empId = Convert.ToInt32(dg["Employee ID"]);
}
感谢您的帮助。
【问题讨论】:
标签: c# wpf wpfdatagrid