GridView RowCommand update send variable to javascript function - asp.net

I have a Gridview that has an update link on it. Once "Edit" is selected from one of the rows the values in that row in the grid change into text boxes and can be edited. The "edit" button disappears and changes into an "update" link. Then the user edits the contents of one (or more than one) of the text boxes and "update" is selected. A JavaScript confirmation box appears asking if the user wants to update the values(s) and the changes are saved or discarded depending upon the choice selected. This is performed by "OnClientClick"
However I want to validate the change server side and pass back a defined error message to the user if the validation has failed. Example; if registered company name in the wrong format has been entered into one of the text boxes in the row selected.
The grid row will then remain in an editable state until the user corrects the error. The operation can be discarded by selecting "Cancel" from the grid row (I already have this functionality).
The C# rowcommand function is:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
// get the primary key id of the clicked row
int id = Convert.ToInt32(e.CommandArgument);
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["moduleConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE suppliers SET Registered_company_name=#registered_company_name WHERE Supplier_code=#supplier_code;";
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
cmd.Parameters.Add("#registered_company_name", SqlDbType.VarChar).Value = myTextBox_registered_company_name.Text;
System.Web.UI.WebControls.Label myLabel = GridView1.Rows[id].FindControl("suppliercode") as System.Web.UI.WebControls.Label;
cmd.Parameters.Add("#supplier_code", SqlDbType.VarChar).Value = Convert.ToInt32(myLabel.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
}
The ASPX is
<asp:LinkButton ID="lnkUpdate" runat="server" CommandArgument='<%# Container.DataItemIndex %>' OnClientClick="return ConfirmOnUpdate();" CommandName="Update" > Update</span></asp:LinkButton>
The javascript is
function ConfirmOnUpdate()
{
if (confirm("Are you sure you want to update this record?"))
return true;
else
return false;
}
Thank you for any replies

Use this code for handling server side validation.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
// get the primary key id of the clicked row
int id = Convert.ToInt32(e.CommandArgument);
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
if (myTextBox_registered_company_name.Text != "") // add your validation in this if block, now it checks textbox is not empty;
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["moduleConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE suppliers SET Registered_company_name=#registered_company_name WHERE Supplier_code=#supplier_code;";
System.Web.UI.WebControls.TextBox myTextBox_registered_company_name = GridView1.Rows[id].FindControl("Registered_company_name") as System.Web.UI.WebControls.TextBox;
cmd.Parameters.Add("#registered_company_name", SqlDbType.VarChar).Value = myTextBox_registered_company_name.Text;
System.Web.UI.WebControls.Label myLabel = GridView1.Rows[id].FindControl("suppliercode") as System.Web.UI.WebControls.Label;
cmd.Parameters.Add("#supplier_code", SqlDbType.VarChar).Value = Convert.ToInt32(myLabel.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
GridView1.EditIndex = -1;
BindData();
}
else
{
ScriptManager.RegisterStartupScript(this,this.GetType(),"Error Message", "alert('TextBox is empty!')",true);
}
}

Related

Submit button to update database, won't work if there is postback stated in page_load

I have a web form page that I am going to query the data from database via selecting different values from dropdown list, after I selected proper value, in the description I want to update the database record while I click the submit button, for example, customer name, and status, there will be only one record coming back and the description will show(I can do it in isPostback and query the database, using SQL DataReader and then call related index element to get it) but when I typed something in the description and click submit, it won't update in the database, but if I don't use if(isPostback) it is working.
P.S. if there is no if(ispostback) case block there,dataUpdate.Update() works well.
So my question is;
protected void btnSubmit_Click(object sender, EventArgs e)
{
dataUpdate.Update();
}
The page_load code:
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
SqlConnection conn1 = new SqlConnection(cxInfo.ConnectionString);
string userInfoQuery1 = "select * from users where id=#id";
SqlCommand userInfo1 = new SqlCommand(userInfoQuery1, conn1);
userInfo1.Parameters.AddWithValue("#id", dropdlCx.SelectedValue);
conn1.Open();
SqlDataReader reader1 = userInfo1.ExecuteReader();
reader1.Read();
if (reader1.HasRows )
{
lblCxId.Text = "" + reader1[0];
SqlConnection conn = new SqlConnection(dataUpdate.ConnectionString);
string userInfoQuery = "select cx_first_name+',' + cx_last_name as 'name',cx_id ,incident_id,description,contact_method from incident where cx_id=#id and status=#status";
SqlCommand userInfo = new SqlCommand(userInfoQuery, conn);
userInfo.Parameters.AddWithValue("#id", lblCxId.Text);
userInfo.Parameters.AddWithValue("#status", dropStatus.SelectedValue);
conn.Open();
SqlDataReader reader = userInfo.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
lblCxId.Text = "" + reader1[0];
txtDesc.Text = (string)reader[3];
radioContact.SelectedValue = (string)reader[4];
desc= (string)reader[3];
}
conn.Close();
}
conn1.Close();
}
if (IsPostBack)
{
lblCxId.Text = dropdlCx.SelectedValue;
/*I want to have txtDesc.txt= database query here, but as long as I add the code here, then the update won't work*/
}
}
So I think there only thing I got stuck is how to let the system know that what I submit is not the thing that he is going to refresh, please accept my value instead of the refresh?

Get submit button id for query

I have a master page in witch more then 30 button like (java,asp,php,sql,c,c++,etc...)
and a have a table of questions. All questions are tagged with one subject like asp,java,etc.
I want to get data according to the click button.
How is it possible?
protected void BindRepeaterData()
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * from question", con);
int count = (int)cmd.ExecuteScalar();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
RepDetails.DataSource = ds;
RepDetails.DataBind();
con.Close();
}
(I think one page for one button is not a good idea.)
There are few ways to capture button click inside Data such as Repeater, GridView, ListView.
Easiest way is to use Command event instead of Click event.
<%-- Let say this button is located inside Repeater control.--%>
<asp:Button ID="DoSomethingButton" runat="server" Text="Home"
OnCommand="DoSomethingButton_Command" CommandArgument="<%# Eval("Id") %>" />
// Retrieve e.CommandArgument from code-behind.
protected void DoSomethingButton_Command(object sender, CommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
}
If you want the ID of the button itself, you can cast the sender back to the Button and get it's ID.
protected void Button1_Click(object sender, EventArgs e)
{
Button button = sender as Button;
string id = button.ID;
}
If I understand you question correctly you could select field from the table according to button information for example in this way. And you could use same event handler for different buttons. Hope this helps.
protected void Btn1_Click(object sender, EventArgs e)
{
Button button = sender as Button;
string question = readData(button.Text);
//do further actions
}
private string readData(string subject)
{
string question = string.Empty;
using (SqlConnection con = new SqlConnection(/*connection_string*/))
{
using (SqlCommand cmd = new SqlCommand("SELECT question from question_table where subject = #subject", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#subject", subject);
con.Open();
object o = cmd.ExecuteScalar();
if (o != null){
question = o.ToString();
}
con.Close();
}
}
return question;
}

delete record from gridview but not from database

I am trying to delete record from grid but not from Database.
I want to set database field ISDeleted 1 when data deleted from gridview but don't want to delete record from db.
My code delete records from both gridview and db.
Where to change in my code-
string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
SqlCommand command;
protected void Page_Load(object sender, EventArgs e)
{
tblAdd.Visible = false;
Label1.Visible = false;
//GridView1.DataBind();
if (!Page.IsPostBack)
{
fillLanguageGrid();
}
}
public void fillLanguageGrid()
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in GridView1.Rows)
{
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chk");
if (chkdelete.Checked)
{
string name= Convert.ToString(GridView1.DataKeys[gvrow.RowIndex].Values["Name"].ToString());
// command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
deleteRecordByName(name);
}
}
fillLanguageGrid();
}
public void deleteRecordByName(string Name)
{
SqlConnection sqlConnection = new SqlConnection(strcon);
using (SqlCommand command = new SqlCommand("[dbo].[hrm_Langauges]", sqlConnection))
{
// define this to be a stored procedure
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#status", SqlDbType.VarChar, 50));
// define the parameter and set its value
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#IsDeleted", SqlDbType.Bit)).Value = 1;
command.Parameters["#status"].Value = "Delete";
//open connection, execute DELETE query, close connection
sqlConnection.Open();
command.ExecuteNonQuery();
sqlConnection.Dispose();
}
}
For that you need to add a column in your respective database table whether to show that record or not.For Ex: add column like Visible int.
Assume if
Visible =1 --> Show that record in gridview
Visible =0 --> Hide that record in gridview
By default make Visible =1 so all records are shown in gridview(write the query like Select ......Where Visible =1).when you try to delete record use update query that need to update Visible column 1 to 0.So your gridview only shows records where visible =1 .That particular deleted record is not shown in your gridview because its Visible column is 0.Try this..

I want my controls value.Insert only one time when I click the button

I have a DropDownlist and a textbox in my page, when I click the button,Button1_Click event fire and get the value od textbox and droppdownlist and send them to my table in database and it shows me the result(new added row in my table in database) in gridview.
my problem is after I click the button if I refresh my page I mean click on reload Current page ,my dropdownlist value and textbox value insert again in my table .
I don't know how solve it?
my gridview use sqldatasource and this is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int brandid = Convert.ToInt32(BrandDropDownList.SelectedValue);
String catname = TextBox2.Text;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "FirstInitialiseCategories";
cmd.Parameters.AddWithValue("#brandid ", brandid);
cmd.Parameters.AddWithValue("#catname ", catname);
try
{
cn.Open();
cmd.ExecuteNonQuery();
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "با موفقیت ثبت شد!";
SqlDataSource2.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = "خطا در ثبت!";
}
finally
{ cn.Close(); }
}
You can do a HTTP redirect (to the same page) once you're done with your first insert, it should solve the issue:
Response.Redirect("samePage.aspx");
what is the first item in your dropdown list? you could set a null value to the first item and when you inserted value to database, you can add code to clear the text box and drop down list.
finally
{
cn.Close();
Label1.Text ="";
ddl.SelectedIndex = 0;
}

Dropdownlist on gridview updating only first value to the database ASP.Net

I am looking for the solution to this problem from many days, please help.
I have a grid view and have five dropdownlist on it. I have edit update and cancel edit buttons on each row.
Drop down list is updating the database, but only first value in the dropdownlist even when user select second, third or any other value from the dropdownlist.
What could possible be the reason for this. Here is my row Edit/ CancelEdit and Updating Events.
protected void gvCustomers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvCustomers.EditIndex = e.NewEditIndex;
BindData();
}
protected void gvCustomers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvCustomers.EditIndex = -1;
BindData();
}
protected void gvCustomers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lblCustId = (Label)gvCustomers.Rows[e.RowIndex].FindControl("cust_id");
DropDownList ddlCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("CSM");
DropDownList ddlSrCsm = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("SrCSM");
DropDownList ddlDE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("DE");
DropDownList ddlAE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("AE");
DropDownList ddlTE = (DropDownList)gvCustomers.Rows[e.RowIndex].FindControl("TE");
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
string sql = "Update SOME_TABLE SET CSM= #CSM, SrCSM= #SrCSM ,DE=#DE,AE=#AE,TE=#TE where cust_id=#cust_id";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#CSM", SqlDbType.VarChar).Value = ddlCsm.SelectedItem.Value;
cmd.Parameters.Add("#SrCSM", SqlDbType.VarChar).Value = ddlSrCsm.SelectedItem.Value;
cmd.Parameters.Add("#AE", SqlDbType.VarChar).Value = ddlAE.SelectedItem.Value;
cmd.Parameters.Add("#DE", SqlDbType.VarChar).Value = ddlDE.SelectedItem.Value;
cmd.Parameters.Add("#TE", SqlDbType.VarChar).Value = ddlTE.SelectedItem.Value;
cmd.ExecuteNonQuery();
}
}
catch
{ }
gvCustomers.EditIndex = -1;
BindData();
}
}
Any help would be greatly appeciated.
Thanks
just fill the dropdowns on the click of edit button and then use on rowupdating event and use ddl.SelectedValue instead of ddl.SelectedItem.Value. You will find the selected values.
Your Drop Downs are probably getting re-set in your Page_Load event. If they are, load them when the page is not in postback, like so:
if(!Page.IsPostBack) {
//set drop downs
}

Resources