C#Datagridview找不到表0

时间:2017-10-10 06:56:24

标签: c# datagridview

这是我的代码:

SqlConnection connection = new SqlConnection(MyConnectionString2);
SqlCommand cmd2;

connection.Open();

   try
   {
   cmd2 = connection.CreateCommand();
   cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (@EmailAddress);");
   cmd2.Parameters.Add("@EmailAddress", SqlDbType.NVarChar);
   cmd2.Parameters["@EmailAddress"].Value = TxbAddEmailUser.Text;
   SqlDataAdapter adap = new SqlDataAdapter(cmd2);
   DataSet ds = new DataSet();
   BindingSource bs = new BindingSource();
   bs.DataSource = ds.Tables[0];
   dataGridView1.DataSource = bs;
   }
   catch (Exception)
   {
      throw;
   }
   TxbAddEmailUser.Clear();  

问题是我的程序给了我错误:

System.IndexOutOfRangeException:找不到tabel 0;

这是我的数据库:

table: tbl_EmailAdress
column: id, int, NOT NULL
column: Email, char(10), NULL  

插入查询有效,我做错了什么?

2 个答案:

答案 0 :(得分:0)

无需这样做,

cmd2.ExecuteNonQuery();

只需使用

$ NODE_ENV=test node yourApp.js

答案 1 :(得分:0)

"找不到表0" 表示INSERT在第一个索引(0)处有空表,因此您无法分配数据源从它。

主要问题是你在这里使用cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (@EmailAddress);"); 命令:

INSERT

cmd2 = connection.CreateCommand(); cmd2.CommandText = ("INSERT INTO tbl_EmailAdress (Email) VALUES (@EmailAddress)"); cmd2.Parameters.Add("@EmailAddress", SqlDbType.NVarChar); cmd2.Parameters["@EmailAddress"].Value = TxbAddEmailUser.Text; cmd2.ExecuteNonQuery(); 命令无意返回SqlDataAdapter的任何结果,您需要使用ExecuteNonQuery

ExecuteNonQuery

请注意,dataGridView1.DataSource仅返回受影响的行(即1行),并且您无法将SqlDataAdapter分配给单个整数值。

如果您想使用SELECT,则需要使用此示例中的cmd2 = connection.CreateCommand(); cmd2.CommandText = ("SELECT * FROM tbl_EmailAdress WHERE Email = @EmailAddress"); cmd2.Parameters.Add("@EmailAddress", SqlDbType.NVarChar); cmd2.Parameters["@EmailAddress"].Value = TxbAddEmailUser.Text; SqlDataAdapter adap = new SqlDataAdapter(cmd2); DataSet ds = new DataSet(); adap.Fill(ds); // fill the data table from adapter BindingSource bs = new BindingSource(); bs.DataSource = ds.Tables[0]; // this time the first table is not null or empty dataGridView1.DataSource = bs; 语句:

{{1}}

类似问题:

Cannot find table 0 error in C#