'对象'不包含ExecuteNonQuery错误的定义

时间:2015-11-13 05:48:25

标签: c# asp.net

我正在使用C#网站,我必须在数据库中动态创建一个表,其名称与用户在注册时提供的用户名相同。

我的代码如下:

protected void btnRegister_Click(object sender, EventArgs e)
{
    string name = txtName.Text;
    string uname = txtUname.Text;
    string mail = txtMail.Text;
    string country = txtCountry.Text;
    string pass = txtPassword.Text;
    SqlConnection con = new SqlConnection(@"Data Source=XYZ\SQLEXPRESS;Initial Catalog=FileHost;Integrated Security=True");
    con.Open();
    SqlDataAdapter da = new SqlDataAdapter("INSERT INTO register(name,username,mail_id,country,password) values('" + name + "','" + uname + "','" + mail + "','"+country+"','"+pass+"')", con);
    DataSet ds = new DataSet();
    da.Fill(ds);
    string sql = "CREATE TABLE 'txtUname.Text'" +
        "(uname VARCHAR(50) CONSTRAINT PkeyMyId PRIMARY KEY, " + "fname VARCHAR(50), path VARCHAR(255))";
    cmd = new SqlCommand(sql, con);
    cmd.ExecuteNonQuery();
    con.Close();
    message.Text = "Registration Successfull!!!";
    txtName.Text = "";
    txtUname.Text = "";
    txtMail.Text = "";
    txtCountry.Text = "";
}

但我收到错误:

  

object不包含ExecuteNonQuery的定义,并且没有可以找到接受类型ExecuteNonQuery的第一个参数的扩展方法object(您是否缺少using指令或一行汇编参考?):cmd.ExecuteNonQuery()

这是什么原因?

3 个答案:

答案 0 :(得分:1)

当您将cmd声明为object时,编译器是绝对正确的:

private object cmd;
// ...
cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery(); // "object" has no "ExecuteNonQuery" method

将变量声明为SqlCommand

private SqlCommand cmd;

答案 1 :(得分:1)

你必须解决很多问题。首先,您必须使查询正确。

string sql = "CREATE TABLE 'txtUname.Text'" +
    "(uname VARCHAR(50) CONSTRAINT PkeyMyId PRIMARY KEY, " + "fname VARCHAR(50), path VARCHAR(255))"; 

更改为

string sql = "CREATE TABLE ["+txtUname.Text+"] +
    "(uname VARCHAR(50) CONSTRAINT PkeyMyId PRIMARY KEY, fname VARCHAR(50), path VARCHAR(255))";

答案 2 :(得分:0)

你可以试试吗

`using SqlCommand cmd = new SqlCommand(sql,con)){
     //put your stuff here 
    cmd.ExecuteNonQuery();
   }`