【问题标题】:C# Using value from Listbox1 for SQL Query to filter Listbox2C# 使用 Listbox1 中的值进行 SQL 查询来过滤 Listbox2
【发布时间】:2020-08-12 16:36:46
【问题描述】:

我有三个 SQL 表 - Team (Id, Name), Player (Id, Name) 和 TeamPlayer (Id, TeamID, PlayerID)。我的表单上还有两个 ListBox,并且希望在第一个 ListBox 上选择项目时过滤第二个 ListBox。

这主要是设置,但我遇到的问题是代码不喜欢在注释行的 LstTeams_SelectedIndexChanged 方法中传递给它的值。

private void Form1_Load(object sender, System.EventArgs e)
    {
        showTeams();
    }

    private void showTeams()
    {
        // Create the SQL Query, and an SqlDataAdapter using this query and sqlConnection declared earlier
        string query = "select * from Team";
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);

        // Get the 'Team' Table and Fill it
        DataTable teamTable = new DataTable();
        sqlDataAdapter.Fill(teamTable);

        // Populate the 'Team' ListBox with the 'Team' Table
        lstTeams.DataSource = teamTable.DefaultView;
        lstTeams.DisplayMember = "Name";
        lstTeams.ValueMember = "Id";
    }

    private void LstTeams_SelectedIndexChanged(object sender, System.EventArgs e)
    {
        string TeamID = lstTeams.GetItemText(lstTeams.SelectedValue);
        MessageBox.Show("TeamID: " + TeamID);

        // Create the SQL Query, and an SqlDataAdapter using this query and sqlConnection declared earlier
        string query = "select * from Player p inner join TeamPlayer tp on p.Id = tp.PlayerID where tp.TeamID = @TeamID";

        SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
        sqlCommand.Parameters.AddWithValue("@TeamID", lstTeams.SelectedValue); // this
        SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand); // causes the dataadapter to error

        // Get the 'Team' Table and Fill it
        DataTable teamTable = new DataTable();
        sqlDataAdapter.Fill(teamTable);

        // Populate the 'Team' ListBox with the 'Team' Table
        lstPlayers.DataSource = teamTable.DefaultView;
        lstPlayers.DisplayMember = "Name";
    }

我的错误是:

System.ArgumentException: 'No mapping exists from object type System.Data.DataRowView to a known managed provider native type.'

我已经查找了一些解决方案,但无法获得有效的结果。

感谢您提供的任何帮助:)。

【问题讨论】:

  • 您映射了一个 DataSource,因此 SelectedValue 将成为一个 DataRowView 对象。您需要将其转换为一个数字。并且不要使用 AddWithValue
  • 使用变量TeamID 作为参数值,但如果列是int,则首先需要将其转换为int。还要指定参数类型的数据类型。

标签: c# sql selectedvalue


【解决方案1】:

经过进一步研究和 cmets 对我的问题提出的一些方向,我发现以下成功:

DataRowView data = lstTeams.SelectedItem as DataRowView;
int TeamID = int.Parse(data["Id"].ToString());

string query = "select * from Player p inner join TeamPlayer tp on p.Id = tp.PlayerID where tp.TeamID = " + TeamID;

在 ListBox1.SelectedIndexChanged 方法内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多