【问题标题】:Show data of table when clicking on a value - SelectionChanged单击值时显示表的数据 - SelectionChanged
【发布时间】:2021-08-17 22:26:09
【问题描述】:

每当我单击 EmployeeRank1 List 列表框中的名称时,我都想在 EmployeeRank1Information 列表框中从表中获取相关数据。但是,我得到了一个例外。下面提供的屏幕截图和代码。

表格

WPF 窗口

例外

我使用过的代码

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 作为参数传递。

标签: c# sql .net database wpf


【解决方案1】:

您可以将Id 传递到查询中,因为这是Employee 的主键

private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if(employeeRank1List.SelectedValue == null)  // less nesting to flip the condition
        return;
    try
    {
        // only select the columns you need
        const string query = @"
select
    Id,
    Name,
    Salary,
    Position,
    Responsibility,
    Age,
    YearsInCompany
from EmployeeRank1 e
where e.Id = @id
";
        // always use a new connection and dispose it
        using (SqlConnection sqlConnection = new SqlConnection(yourConnectionString))
        // Create an SqlCommand and connect to the database
        using (SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
        {
            // always specify parameter type (and length for strings)
            sqlCommand.Parameters.Add("@id", SqlDbType.Int).Value = ((DataRow)employeeRank1List.SelectedValue)["Id"];
            // how do you get the Id column??
            DataTable employeeRank1InformationTable = new DataTable();
            conn.Open();
            using (SqlDataReader reader = sqlCommand.ExecuteReader())
            {
                employeeRank1InformationTable.Load(reader);
            }
        } // close connection as quick as you can

        // you can only set one column to display
        employeeRank1Information.DisplayMemberPath = "Name";
        employeeRank1Information.SelectedValuePath = "Id";

        employeeRank1Information.ItemsSource = employeeRank1InformationTable.DefaultView;
    }
    catch (Exception exception)
    {
        // show what is the error
        MessageBox.Show(exception.Message);
    }
}

【讨论】:

  • 谢谢,这真的很有帮助,我学到了很多东西。传递 id 作为参数使其工作。我想出了一个自己的方法,贴在下面。
【解决方案2】:

你已经声明了这些没有价值的where条件

AND Salary = @salary AND
Responsibility = @responsibility AND
Position = @position AND
Age = @age AND
YearsInCompany = @yearsInCompany

您需要在执行查询之前填写它们

sqlCommand.Parameters.AddWithValue("@Salary", <VALUE FROM TABLE>);

由于您尚未指定如何填充网格视图或表格, 您需要自己获取以下值

您的 SQL 查询包含 6 个条件。

select * from EmployeeRank1 where Name = @name AND Salary = @salary AND Responsibility = @responsibility AND Position = @position AND Age = @age AND YearsInCompany = @yearsInCompany. 

但您只使用 - 填充了一个

sqlCommand.Parameters.AddWithValue("@name", employeeRank1List.SelectedValue);

所以基本上点击列表项时查询等于这个

select * from EmployeeRank1 where Name = <LitsView Item>
AND Salary = UNDEFINED  
AND Responsibility = UNDEFINED 
AND Position = UNDEFINED 
AND Age = UNDEFINED  
AND YearsInCompany = UNDEFINED;

现在这里的 UNDEFINED 使它成为 SQL 语法错误,因为缺少标量变量。为了让它工作,这里有一个解决方法让你了解它是如何工作的-

在你的代码中改变这一行

string query = "select * from EmployeeRank1 where Name = @name AND Salary = @salary AND Responsibility = @responsibility AND Position = @position AND Age = @age AND YearsInCompany = @yearsInCompany";

到这里

string query = "select * from EmployeeRank1 where Id = @name";

在您尝试后,它应该会得到不准确的结果。使其正常工作,填充 SQL 代码中的其余 where 条件

另外,使用主键/唯一键来定位记录,而不是使用@NAME

【讨论】:

  • “您需要在执行查询之前将它们归档”是什么意思。我在 中写什么。对不起,如果我的问题不是最聪明的,但我真的很困惑。
  • 我更新了我的答案,因为我无法在这里发表评论。在开始进行此类编码之前,您确实需要了解有关 SQL 和标量变量的更多信息。使用w3schools.com
  • 谢谢,这真的很有帮助,我学到了很多东西。我知道我的 SQL 知识是滞后的,但是我需要用它做一个项目并且时间有限。但是,我设法自己弄清楚了,在下面发布了我的解决方法。
【解决方案3】:

我设法通过使用多个列表框而不是一个来使其工作。此外,在查询中,我只选择了作为主键的 id,然后添加了多个 try-catch 块以填充我创建的那些列表框。工作程序的截图,以及代码

计划

代码

// a method that shows information for employees that are rank 1
    private void ShowEmployeeRank1Information()
    {
        // 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 Id = @id";

            // 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("@id", employeeRank1List.SelectedValue);

                // create a new data table that allows us
                // to store data from tables within objects
                DataTable employeeRank1PositionTable = new DataTable();

                // fill the sqlDataAdapter with all the
                // information from the query(from the EmployeeRank1 table)
                sqlDataAdapter.Fill(employeeRank1PositionTable);

                // set the content of the employeeRank1List
                // to be the content from each column in the table
                employeeRank1PositionList.DisplayMemberPath = "Position";

                employeeRank1PositionList.SelectedValuePath = "Id";

                employeeRank1PositionList.ItemsSource = employeeRank1PositionTable.DefaultView;
            }
        }
        catch (Exception e)
        {
            // show what is the error
            MessageBox.Show(e.ToString());
        }
        try
        {
            // create a query and select everything from "EmployeeRank1" table
            // except the Password and GenericPassword columns
            string query = "select * from EmployeeRank1 where Id = @id";

            // 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("@id", employeeRank1List.SelectedValue);

                // create a new data table that allows us
                // to store data from tables within objects
                DataTable employeeRank1AgeTable = new DataTable();

                // fill the sqlDataAdapter with all the
                // information from the query(from the EmployeeRank1 table)
                sqlDataAdapter.Fill(employeeRank1AgeTable);

                // set the content of the employeeRank1List
                // to be the content from each column in the table
                employeeRank1AgeList.DisplayMemberPath = "Age";

                employeeRank1AgeList.SelectedValuePath = "Id";

                employeeRank1AgeList.ItemsSource = employeeRank1AgeTable.DefaultView;
            }
        }
        catch (Exception e)
        {
            // show what is the error
            MessageBox.Show(e.ToString());
        }
        try
        {
            // create a query and select everything from "EmployeeRank1" table
            // except the Password and GenericPassword columns
            string query = "select * from EmployeeRank1 where Id = @id";

            // 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("@id", employeeRank1List.SelectedValue);

                // create a new data table that allows us
                // to store data from tables within objects
                DataTable employeeRank1ResponsibilityTable = new DataTable();

                // fill the sqlDataAdapter with all the
                // information from the query(from the EmployeeRank1 table)
                sqlDataAdapter.Fill(employeeRank1ResponsibilityTable);

                // set the content of the employeeRank1List
                // to be the content from each column in the table
                employeeRank1ResponsibilityList.DisplayMemberPath = "Responsibility";

                employeeRank1ResponsibilityList.SelectedValuePath = "Id";

                employeeRank1ResponsibilityList.ItemsSource = employeeRank1ResponsibilityTable.DefaultView;
            }
        }
        catch (Exception e)
        {
            // show what is the error
            MessageBox.Show(e.ToString());
        }

        try
        {
            // create a query and select everything from "EmployeeRank1" table
            // except the Password and GenericPassword columns
            string query = "select * from EmployeeRank1 where Id = @id";

            // 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("@id", employeeRank1List.SelectedValue);

                // create a new data table that allows us
                // to store data from tables within objects
                DataTable employeeRank1YearsInCompanyTable = new DataTable();

                // fill the sqlDataAdapter with all the
                // information from the query(from the EmployeeRank1 table)
                sqlDataAdapter.Fill(employeeRank1YearsInCompanyTable);

                // set the content of the employeeRank1List
                // to be the content from each column in the table
                employeeRank1YearsInCompanyList.DisplayMemberPath = "YearsInCompany";

                employeeRank1YearsInCompanyList.SelectedValuePath = "Id";

                employeeRank1YearsInCompanyList.ItemsSource = employeeRank1YearsInCompanyTable.DefaultView;
            }
        }
        catch (Exception e)
        {
            // show what is the error
            MessageBox.Show(e.ToString());
        }
    }

    private void employeeRank1List_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if(employeeRank1List.SelectedValue != null)
        {
            ShowEmployeeRank1Information();
        }
    }

【讨论】:

  • 你有3次相同的代码。您可以只返回一个 DataTable 并在所有 3 个地方引用它。您还需要创建和处理您的连接,不要不要缓存它。
猜你喜欢
  • 1970-01-01
  • 2018-06-14
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多