Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用for C语句在列表框中获取我的所有数据库表值#_C#_Database_Ms Access_For Loop_Listbox - Fatal编程技术网

C# 如何使用for C语句在列表框中获取我的所有数据库表值#

C# 如何使用for C语句在列表框中获取我的所有数据库表值#,c#,database,ms-access,for-loop,listbox,C#,Database,Ms Access,For Loop,Listbox,作为C#的初学者,我在从数据库表中获取所有值(以及仅获取值,而不是字段名)并将其列在列表框中时遇到了一些问题 我做了一些研究,发现我可以通过以下代码获得特定表的所有字段名: try { connection.Open(); OleDbCommand command = new OleDbCommand(); command.Connection = connection; string query = "select * from MyTable where Mont

作为C#的初学者,我在从数据库表中获取所有值(以及仅获取值,而不是字段名)并将其列在列表框中时遇到了一些问题

我做了一些研究,发现我可以通过以下代码获得特定表的所有字段名:

try
 {
   connection.Open();
   OleDbCommand command = new OleDbCommand();
    command.Connection = connection;
   string query = "select * from MyTable where Month='January'";

   command.CommandText = query;
   OleDbDataReader reader = command.ExecuteReader();
   var columns = listBox5;

   for (int i = 0; i < reader.FieldCount; i++)
   {
      if (reader.GetName(i) != "Month" && reader.GetName(i) != "Id")
      {
                        columns.Items.Add(reader.GetName(i));
      }    
   }


   connection.Close();
}
catch (Exception ex)
{
     MessageBox.Show("Error" + ex);
}

您需要在读卡器上调用
Read()
,然后才能读取记录:

var columns2 = listBox6;

while (reader.Read())
{
    for (int i = 0; i < reader.FieldCount; i++)
    {    
        columns2.Items.Add(reader.GetValue(i).ToString());    
    }
}
var columns2=listBox6;
while(reader.Read())
{
对于(int i=0;i
发件人:

将SqlDataReader前进到下一条记录。SqlDataReader的默认位置在第一条记录之前。因此,您必须调用Read来开始访问任何数据


糟糕的是,我收到以下错误:ErrorSystem.InvalidOperationException:第行/第列的数据不存在(此行:columns2.Items.Add(reader.GetValue(I.ToString());)非常感谢!很好用!
columns2.Items.Add(reader.GetValue(i).ToString());
var columns2 = listBox6;

while (reader.Read())
{
    for (int i = 0; i < reader.FieldCount; i++)
    {    
        columns2.Items.Add(reader.GetValue(i).ToString());    
    }
}