【问题标题】:How to pull integer values from SQL Server database to C# Combobox?如何将整数值从 SQL Server 数据库提取到 C# 组合框?
【发布时间】:2020-01-23 18:20:35
【问题描述】:

下面的例子展示了选择随机的 combobobx 项目后会发生什么。 Sql 查询已成功运行,但是我收到错误“指定的强制转换不是有效的 c#”。

组合框 listaPrzedmiotow 以字符串形式存储学校科目列表。 组合框 listaIndeksów 应该存储学生索引列表。在 SQL Server 数据库中 student indices 列接受整数,所以我不知道为什么 .GetInt64(i) 方法对此无效。

private void listaPrzedmiotow_SelectedIndexChanged(object sender, EventArgs e)
        {
            MessageBox.Show(listaPrzedmiotow.SelectedItem.ToString());
            SqlCommand sqlCommand = new SqlCommand("select studenci.NUMER_INDEKSU from dbo.oceny inner join studenci on studenci.numer_indeksu = oceny.numer_indeksu inner join dbo.przedmioty on przedmioty.przedmiot_id = oceny.przedmiot_id where przedmioty.NAZWA_PRZEDMIOTU = '" + listaPrzedmiotow.SelectedItem.ToString() + "'", sqlConnection);
            SqlDataReader indexesList = sqlCommand.ExecuteReader();

            while (indexesList.Read())
            {
                for (byte i = 0; i < indexesList.FieldCount; i++)
                {
                    listaIndeksów.Items.Add(indexesList.GetInt64(i));
                }
            }
            indexesList.Close();
            indexesList.Dispose();
        }

【问题讨论】:

    标签: c# sql wpf combobox


    【解决方案1】:

    可能发生错误是因为您在 indexList.GetInt64() 处传递一个字节。

    如果您查看文档 https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.getint64?view=netframework-4.8,就会发现

    尝试在 for 循环中将字节更改为 int。如果这不起作用,您可以尝试 Convert.ToInt32() 以及您在循环中捕获的值

    【讨论】:

      猜你喜欢
      • 2013-05-24
      • 2014-12-06
      • 2016-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-04
      • 2011-10-04
      相关资源
      最近更新 更多