【发布时间】:2021-08-17 22:26:09
【问题描述】:
每当我单击 EmployeeRank1 List 列表框中的名称时,我都想在 EmployeeRank1Information 列表框中从表中获取相关数据。但是,我得到了一个例外。下面提供的屏幕截图和代码。
我使用过的代码
private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(employeeRank1List.SelectedValue != null)
{
// use a try-catch, in case we run into an
// error while digging into the database
try
{
// create a query and select everything from "EmployeeRank1" table
// except the Password and GenericPassword columns
string query = "select * from EmployeeRank1 where Name = @name AND Salary = @salary AND Responsibility = @responsibility AND Position = @position AND Age = @age AND YearsInCompany = @yearsInCompany";
// Create an SqlCommand and connect to the database
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
// create a connection to the database and run sqlCommand
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand);
// use the sqlDataAdapter
using (sqlDataAdapter)
{
// add a value to the EmployeesRank1 Information table, once an item in the EmployeesRank1 table is clicked
sqlCommand.Parameters.AddWithValue("@name", employeeRank1List.SelectedValue);
// create a new data table that allows us
// to store data from tables within objects
DataTable employeeRank1InformationTable = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the EmployeeRank1 table)
sqlDataAdapter.Fill(employeeRank1InformationTable);
// set the content of the employeeRank1List
// to be the content from each column in the table
employeeRank1Information.DisplayMemberPath = "Salary";
employeeRank1Information.DisplayMemberPath = "Position";
employeeRank1Information.DisplayMemberPath = "Responsibility";
employeeRank1Information.DisplayMemberPath = "Age";
employeeRank1Information.DisplayMemberPath = "YearsInCompany";
employeeRank1Information.SelectedValuePath = "Id";
employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView;
}
}
catch (Exception exception)
{
// show what is the error
MessageBox.Show(exception.ToString());
}
}
}
【问题讨论】:
-
你为什么不直接传递
Id作为参数,我假设那是主键?此外,您应该使用using处理您的连接对象。 -
是的,Id 是主键。您能否详细说明如何将 Id 作为参数传递。