Click here to Skip to main content
16,018,202 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I was programming on update of grid view using select link button. I have linked select to another form and put an update button.

This is my table

news_id \\ int \\ No \\ PRI \\Auto_increment
Name \\ varchar(500) \\ No
news_date \\Date \\ No
description \\Text \\ No
Status \\ int \\ No
created_date \\Date \\ No

This is my code:


protected void btnupdate_Click(object sender, EventArgs e)
{
try
{

SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
con.Open();

SqlCommand cmd = new SqlCommand();
string ssql;
ssql = "Update news where news_id=@news_id(";
ssql = ssql + "'" + Convert.ToString(txtname.Text) + "'";
ssql = ssql + ",'" + Convert.ToString(startdate) + "'";
ssql = ssql + ",'" + Convert.ToString(txtdescription.Text) + "'";
ssql = ssql + ",'" + Convert.ToString(drpstatus.SelectedValue) + "'";
ssql = ssql + ",'" + Convert.ToString(lblcreateddate.Text) + "'";

ssql = ssql + ")";

cmd.CommandText = ssql;
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();



BindUserDetails();

}
catch (Exception ex)
{

}
}

I don't want to use news_id because I have given it as auto increment and so the user can't update it. So in the query I have written it won't know from where to find the news.

Please help.
Posted
Comments
ZurdoDev 18-Feb-14 12:03pm    
Your update query needs to have the id but you don't need to expose the id to the user.
Richard MacCutchan 18-Feb-14 12:15pm    
Don't use Convert.ToString on text fields. And don't use string concatenation for SQL commands, use proper type-safe parameterization.

1 solution

You will need the news_id for reverting back to the database. You do not have to show it to the user by assigning it to the "DataKeynames" property of the gridview. Check this out:
DataKeyNames[^]
Refer to this for CRUB using gridview: insert-update-and-delete-using-grid-view-and-objectdatasource.aspx[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900