【问题标题】:how to retrieve data from database in combobox c#如何在组合框c#中从数据库中检索数据
【发布时间】:2014-07-14 13:39:05
【问题描述】:

我写了这段代码,但我不知道为什么这行会出错!

 String sname = dr.GetString ("name"); 

我的代码:

SqlConnection cn = new SqlConnection(
    "Data Source=.;Initial Catalog=logindb;Integrated Security=True");

string query1 = "select * from tbllogin";
SqlCommand cmd = new SqlCommand(query1);
SqlDataReader dr;

try
{
    cn.Open();
    dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        String sname = dr.GetString("name");
        comboBox1.Items.Add(sname);
    }
}
catch (Exception e)
{
    // do smth about exception
}

【问题讨论】:

  • 我想看看你的错误信息,但是今晚我的水晶球坏了,你能帮我们写一下吗?
  • 您是否尝试在 GetString() 中给出索引?
  • 如何进入?使用 getstring 索引

标签: c# ado.net sqlcommand


【解决方案1】:

首先你必须再次检查:

SqlConnection cn = new SqlConnection(
"Data Source=.;Initial Catalog=logindb;Integrated Security=True");

Data Source=.;这是错误的,它会给你一个错误。

之后,您可以使用下面的代码来实现您想要的。下面的代码也使用using 语句来处理连接。

using (
SqlConnection connection = new SqlConnection(strCon)) // strCon is the string containing connection string
{
    SqlCommand command = new SqlCommand("select * from tbllogin", connection);
    connection.Open();
    DataReader reader = command.ExecuteReader();
    if (reader.HasRows)
    {
        while (reader.Read())
        {
            comboBox1.Items.Add(reader.GetString(int index)); // index of column you want, because this method takes only int
        }
    } 
    reader.Close();
}

【讨论】:

  • 这段代码出错了!输入索引需要什么?
  • 如果你有一个包含 2 列的表,并且你想获得第一列,那么你写 (0) 作为索引...
  • 很抱歉回复晚了。我忘了检查这个问题,我只是检查我的旧答案,所以我检查了这个并根据您的要求更新了我的答案。
【解决方案2】:

MSDN 表示SqlDataReader.GetString 方法接受int 作为参数,这是列的索引。

你需要的是这个:

while (dr.Read())
{
    String sname = (string)dr["name"];
    comboBox1.Items.Add(sname);
}

这是你的代码:

    SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=logindb;Integrated Security=True");
    string query1 = "select * from tbllogin"; SqlCommand cmd = new SqlCommand(query1); SqlDataReader dr;
    try {
        cn.Open(); dr = cmd.ExecuteReader();
        while (dr.Read())
        { String sname = (string)dr["name"];
        comboBox1.Items.Add(sname);
        }
    }
    catch (Exception e) { MessageBox.Show(e.Message, "An error occurred!"); }

catch 块没有正确写入,您错过了(Exception e) 部分。

【讨论】:

  • 谢谢:亲爱的朋友:但你的代码:不能正常工作!!!!请给我完整的代码!!!!我是初学者!!!!同上代码!!!
  • 它给出了什么错误(如果有的话)?它输出什么?您的预期输出?
  • 不报任何错误!但是表格中没有显示我写的代码:我再次写:也许问题是我的代码
  • 请编辑你的OP并添加代码,cmets不是写代码的地方。
  • 正如我之前所说,您的连接字符串无效。 Data Source 参数不正确。
【解决方案3】:

(惊奇地)GetString 只接受一个索引作为参数。 见MSDN

public override string GetString(int i)

没有其他签名:-(

你可以写:

String sname = dr.Item["name"].ToString();

【讨论】:

    猜你喜欢
    • 2016-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 2013-05-24
    相关资源
    最近更新 更多