【问题标题】:There's no row at posistion [0]位置 [0] 处没有行
【发布时间】:2016-05-14 08:15:56
【问题描述】:

我有以下代码:

private void ReturnForm_Load(object sender, EventArgs e)
{
        string select = "SELECT TransactionID FROM [Transaction] WHERE ReturnDate = '" + null + "'";
        comboBox1.DisplayMember = "TransactionID";
        comboBox1.ValueMember = "TransactionID";
        comboBox1.DataSource = con.FillTable(select);
        comboBox1.SelectedIndex = -1;
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        int rentduration;
        int lateduration;
        double extracharge;
        int totalprice;
        int price;

        string a = "SELECT StaffID,CarID,ClientName,StartDate,EndDate FROM [Transaction] WHERE TransactionID = '" + comboBox1.Text + "'";
        string b = "SELECT * FROM MsCar WHERE CarrID = '" + label12.Text + "'";

        DataTable dt = con.FillTable(a);
        DataTable da = con.FillTable(b);
        dataGridView1.DataSource = dt;

            label10.Text = dt.Rows[0][1].ToString();
            label11.Text = dt.Rows[0][3].ToString();
            label12.Text = dt.Rows[0][2].ToString();
            label13.Text = dt.Rows[0][4].ToString();
            label14.Text = dt.Rows[0][5].ToString();
            label15.Text = DateTime.Now.ToString("MM dd YYYY");
}

当我运行表单时,此代码会引发错误:

位置 0 处没有行。

但是当我使用datagridview时:

datagridview1.datasource = dt;

显示所有数据。

请帮帮我。

【问题讨论】:

  • SQL Injection alert - 您应该将您的 SQL 语句连接在一起 - 使用 参数化查询 来避免 SQL 注入
  • 尝试通过在以下行插入断点来跟踪您的代码:DataTable dt = con.FillTable(a); 并查看数据表的第一行将填充什么以及dt.Rows[0][1].ToString(); 内部的内容
  • 并继续跟踪以查找任何可能导致问题的事件触发。
  • 这段代码是你最近自己写的吗?似乎 DataTable 没有正确创建,这意味着您有一个表,但只有标题名称。
  • 你能不能也展示你的 FillTable(string string) 方法?

标签: c# sql datatable datarow


【解决方案1】:

在提交后尝试使用您的组合框选择 组合框选择的索引更改也会在关闭表单时发生,并且选择的索引更改事件函数用于空字符串。在向SqlDataAdapter 发送数据时也要删除空格。

使用

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)

而不是

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

 string a = "SELECT StaffID,CarID,ClientName,StartDate,EndDate FROM [Transaction] WHERE TransactionID = '" + comboBox1.Text.Trim() + "'";

【讨论】:

    猜你喜欢
    • 2015-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2011-12-09
    • 2014-03-06
    • 1970-01-01
    • 2019-06-03
    相关资源
    最近更新 更多