In my application am allowing the user to delete an entire row from the grid view when he clicks on delete button. but am getting an error in delete query. Error is "Invalid column name" my code is as follows:
<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# code is:
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();
}
(@"Data Source=CHINNU-PC\SQLEXPRESS; Initial Catalog= CarDetails; Integrated Security=True");like this(@"Data Source=.\SQLEXPRESS; Initial Catalog= CarDetails; Integrated Security=True");- see how I replaced the computer name with a .? Now your code wont break if you try to set it up on a computer that isn't called CHINNU-PC.