【问题标题】:DataTable Column data to combobox errorDataTable 列数据到组合框错误
【发布时间】:2014-04-28 02:53:28
【问题描述】:

我想在组合框中显示数据表列中的所有数据。表格是订购新库存并保存到数据库中。

我按照这个教程http://youtu.be/cdkDHkXyVFI
我收到 2 条错误消息:

Error   1   The best overloaded method match for 'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments  
Error   2   Argument 1: cannot convert from 'string' to 'int'

代码:

public partial class neworderForm : Form
{

public neworderForm()
{
    InitializeComponent();
    fillCombo();
}
void fillCombo()
{
    string constring = @"Data Source=|DataDirectory|\LWADataBase.sdf";
    string Query = "select * from stockTBL; ";
    SqlCeConnection conDataBase = new SqlCeConnection(constring);
    SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
    SqlCeDataReader myReader;
    try
    {
        conDataBase.Open();
        myReader = cmdDataBase.ExecuteReader();

        while (myReader.Read())
        {
            string sName = myReader.GetString("[Item Name]");
            comboItem.Items.Add(sName);
        }

        //displays a system error message if a problem is found
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

错误出现在string sName = myReader.GetString("[Item Name]");

【问题讨论】:

  • 两个错误都是说:使用整数列索引作为GetString 参数,而不是列名。
  • 你能详细说明一下怎么做吗?

标签: c# mysql winforms combobox


【解决方案1】:

不要在该函数中使用字符串。如果您知道基于零的列索引,则将其传递到那里

【讨论】:

    【解决方案2】:

    【讨论】:

    • 完美运行。使用代码中的“[]”,它会打开一个消息框,上面写着“[Item Name]”,所以我删除了它们,它按照我的需要运行!谢谢安德烈。
    • 比我快几秒!是的,确实是这样。
    • 我会这样做,虽然@LeeCambl 的回答非常相似,但我会使用你的,因为你先写了!除非你们想为此而战;)
    • 尽管 Lee 保留你的答案,其他人会发现它的信息量很大。
    【解决方案3】:

    System.Data.Common.DbDataReader 上的 GetString() 方法采用列号(一个 int)以将 int 指定的列的值作为字符串返回。这个 int 被称为“序数”。你可以做的是修改你的代码来阅读:

    string sName = myReader.GetString(myReader.GetOrdinal("[Item Name]"));
    

    GetOrdinal() 位将返回用于 GetString() 位的列号。

    有意义吗?对于这样的内容,我倾向于阅读一些 Intellisense 内容,这些内容会在您键入时弹出以查看我需要哪种方法 - 我永远记不住所有内容!

    【讨论】:

    • 现在解释清楚了,我不明白他是如何在视频教程中使用它的。哦,好吧,现在对我来说完美无缺。
    猜你喜欢
    • 1970-01-01
    • 2013-04-23
    • 2020-02-14
    • 2011-12-14
    • 1970-01-01
    • 2018-02-15
    • 2019-03-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多