2013-08-22 45 views
0

在我的应用程序中,当他点击删除按钮时,允许用户从网格视图中删除整行。但是在删除查询时出现错误。错误是“无效的列名” 我的代码如下:使用C#在asp.net中删除查询#

<asp:GridView ID="GridView1" runat="server" DataKeyNames="Username" AutoGenerateColumns="false" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowDeleting="GridView1_RowDeleting" > 
<Columns> 
<asp:BoundField DataField="UserName" HeaderText="UserName" ReadOnly="true" /> 
<asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="true" /> 
<asp:BoundField DataField="Password" HeaderText="Password" ReadOnly="true" /> 
<asp:BoundField DataField="Email" HeaderText="Email" ReadOnly="true" /> 
<asp:CommandField ShowDeleteButton="true" /> 
</Columns> 
</asp:GridView> 

C#代码:

SqlConnection conn = new SqlConnection(@"Data Source=CHINNU-PC\SQLEXPRESS; Initial Catalog= CarDetails; Integrated Security=True"); 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      gvbind(); 
     } 
    } 

    protected void gvbind() 
    { 
     conn.Open(); 
     SqlCommand cmd = new SqlCommand("Select * From [User]", conn); 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataSet ds = new DataSet(); 
     da.Fill(ds); 
     conn.Close(); 
     if (ds.Tables[0].Rows.Count > 0) 
     { 
      GridView1.DataSource = ds; 
      GridView1.DataBind(); 
     } 
    } 

public void Delete(string UserName) 
     { 
      string sql = "Delete From [User] Where UserName=" + UserName; 

      conn.Open(); 
      SqlCommand cmd = new SqlCommand(sql, conn); 
      cmd.ExecuteNonQuery(); 
      conn.Close(); 
      conn.Dispose(); 
     } 
     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) 
     { 
      Delete(GridView1.DataKeys[e.RowIndex].Values[0].ToString()); 
      gvbind(); 
     } 
+0

旁注:你可以写这个'(@“数据源= CHINNU-PC \ SQLEXPRESS;初始目录= CarDetails;集成安全= True“);'像这样'(@”Data Source =。\ SQLEXPRESS; Initial Catalog = CarDetails; Integrated Security = True“);' - 看我如何用a。替换计算机名称?如果您尝试在未调用CHINNU-PC的计算机上设置它,现在您的代码不会中断。 – rtpHarry

回答

4

你会得到许多关于SQL注入等意见....

但是,为了回答 - 您需要在SQL语句中用单引号包装UserName

所以这 -

string sql = "Delete From [User] Where UserName=" + UserName; 

应该是这样的:

string sql = "Delete From [User] Where UserName='" + UserName + "'"; 
+0

SQL注入! SQL注入! SQL注入! :)但严肃地说,不要仅仅考虑Darren的回复,你需要修复这个安全漏洞 - 你的网站可能会被黑客入侵。我确信这个特定的页面是在一个锁定的管理面板中,但这并不意味着你是安全的,并不意味着你没有可能在前端代码中犯这个错误。 – rtpHarry