【问题标题】:Error showing SQL statement显示 SQL 语句时出错
【发布时间】:2015-01-16 08:38:48
【问题描述】:

我在名为“Database”的数据库中创建了一个名为“Client”的表,但是当我尝试显示某个选择查询的结果时,它给了我错误

"错误 1 ​​'System.Data.DataRow' 是一个 'type' 但被用作'variable'

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        string myConnection = 
            "datasource=localhost;port=3306;username=abc;password=xyz";

        MySqlConnection myConn = new MySqlConnection(myConnection);
        MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
        myDataAdapter.SelectCommand = new MySqlCommand(
            "select * from  Database.Client", myConn);

        MySqlCommandBuilder cb = new MySqlCommandBuilder(myDataAdapter);
        myConn.Open();

    //    MessageBox.Show("Connected");

        DataSet ds = new DataSet();
        DataRow dr = new DataRow();
        DataTable dt;

        myDataAdapter.Fill(ds, "Client");
        dt = ds.Tables["Client"];
        dr = dt.Rows[0];

        dg.DataSource = ds.Tables["Client"];

        myConn.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

【问题讨论】:

  • 异常在哪里引发?代码似乎没问题。
  • 你在哪一行得到这个错误?查看您的代码,没有任何东西可以引发该异常。

标签: c# sql select


【解决方案1】:

DataRowno public constructor

所以这不起作用:

DataRow dr = new DataRow();

而是稍后从DataRowCollection-indexer 初始化它:

DataRow dr = null;
// ...
dr = dt.Rows[0];

但是,编译器错误应该是不同的( .... 由于其保护级别而无法访问)。

【讨论】:

    【解决方案2】:

    您不能创建新的实例 DataRow。所以删除这一行:

    DataRow dr = new DataRow();
    

    改为在这一行执行此操作:

    var dr = dt.Rows[0];
    

    或者你可以像这样输入识别它:

    DataRow dr = dt.Rows[0];
    

    【讨论】:

    • 你可以声明一个DataRow类型的变量,但是你不能通过调用构造函数来创建一个新的实例
    • @ThorstenDittmar:你是对的。我更新答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2022-09-26
    相关资源
    最近更新 更多