2016-03-11 34 views
0

我有一个包含大约40行的MySQL数据库。在单独的文本框中显示从数据库中检索的行

我想将“值”分别读入它自己的文本框中。

我至今

using (var cmd2 = new OdbcCommand("select value,entity_id,store_id from  catalog_category_entity_varchar where attribute_id = 41 ", con)) 
{ 
    con.Open(); 

    using (var reader = cmd2.ExecuteReader()) 
    { 
     while (reader.HasRows) 
     { 
      int count = reader.FieldCount; 
      for (int i = 0; i < count; i++) 
      { 
       while (reader.Read()) 
       { 

        textBox[i].txt = (reader[0].ToString()); 

        this.Controls.Add(textBox[i].txt); 

        reader.NextResult(); 

       } 
      } 
     } 

我只得到了第一个记录到一个文本框。

假设行数未知。 如果有40行,则必须有40个文本框。

我已经编辑我的代码:

using (var reader = cmd2.ExecuteReader()) 
       { 
        int i = 0; 
        while (reader.HasRows) 
        { 
         TextBox txt = new TextBox(); 
         txt.Text = reader.GetString(0); 
         this.Controls.Add(txt); 

         textBox[i].txt = (reader.GetString(0)); 
         this.Controls.Add(textBox[i].txt); 
         reader.NextResult(); 
         i++; 
        } 
       } 

,我得到的错误是:错误 - 名称的文本框不会在当前的背景下存在

+1

不知道这与MySQL有什么关系。 – user1666620

+0

我正在使用Mysql来获取数据。 – Danie

+0

@丹尼,但这是不相关的问题。 \t请阅读[**如何提问**](http://stackoverflow.com/help/how-to-ask) \t \t这里是[** START **]( http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)了解如何提高您的问题质量并获得更好的答案。 –

回答

0

如果您textBox是控件数组

con.Open(); -- you need open the connection before the command 

using (var cmd2 = new OdbcCommand("select value,entity_id,store_id 
            from catalog_category_entity_varchar 
            where attribute_id = 41 ", con)) 
{ 
     using (var reader = cmd2.ExecuteReader()) 
     { 
      int i = 0; 
      while (reader.Read()) 
      { 
       TextBox txt = new TextBox(); 
       txt.Text = reader.GetString(0); 
       txt.Location.x = 100; 
       txt.Location.y = 100 * i; 
       this.Controls.Add(txt); 
       i++; 
      } 

如果您还没有创建文本框已经需要

TextBox txt = new TextBox(); 
txt.Text = reader.GetValue(0); 
txt.Location.x = 100; 
txt.Location.y = 100 * i; 
this.Controls.Add(txt); 
+0

我试过了,错误 - 名称文本框在当前上下文中不存在。 – Danie

+0

你有一个'textbox'数组吗?否则,您需要按照我的说明创建每个控件。 –

+0

reader.GetValue(0)给我错误不能将类型'object'隐式转换为'string' – Danie

相关问题