textbox value remains unchanged on form submission in edit profile page - c#

i am trying to create a edit profile page so when the page loads first i am filling all text boxes values as the value present in the database for the particular user.i am doing this using the code:
DBconn obj1 = new DBconn();
String sql1 = "select* from users where user_id='" + Session["user_id"].ToString() + "'";
DataTable dt = new DataTable();
dt = obj1.getdatatable(sql1);
if (dt.Rows.Count > 0)
{
referal_id.Text = dt.Rows[0]["referal_id"].ToString();
name.Text = dt.Rows[0]["name"].ToString();
password.Text = dt.Rows[0]["password"].ToString();
email.Text = dt.Rows[0]["email"].ToString();
mobile.Text = dt.Rows[0]["mobile"].ToString();
city.Text = dt.Rows[0]["city"].ToString();
state.Text = dt.Rows[0]["state"].ToString();
pincode.Text = dt.Rows[0]["pincode"].ToString();
sec_ques.Text = dt.Rows[0]["securityq"].ToString();
answer.Text = dt.Rows[0]["answer"].ToString();
age.Text = dt.Rows[0]["age"].ToString();
gender.Text = dt.Rows[0]["gender"].ToString();
user_id.Text = dt.Rows[0]["user_id"].ToString();
address.Text = dt.Rows[0]["address"].ToString();
date_of_joining.Text = dt.Rows[0]["date_of_joining"].ToString();
user_type.Text = dt.Rows[0]["user_type"].ToString();
}
now this is filling all the text boxes with the values .
when user edits some values in some textbox and resubmits the form the database is getting updated implementing the code:
protected void LinkButton1_Click(object sender, EventArgs e)
{
int i;
DBconn obj2 = new DBconn();
String sql2 = "update users set name='"+name.Text+"',address='"+address.Text+"',age='"+age.Text+"',gender='"+gender.Text+"',email='"+email.Text+"',mobile='"+mobile.Text+"',securityq='"+sec_ques.Text+"',answer='"+answer.Text+"',city='"+city.Text+"',state='"+state.Text+"',pincode='"+pincode.Text+"' where user_id='"+Session["user_id"].ToString()+"'";
i = obj2.executeDML(sql2);
if (i > 0)
{
Label1.Visible = true;
Image2.Visible = true;
Label1.Text = "Updated successfully!";
}
else
{
Label1.Visible = true;
Label1.Text = "Oops Update was unsuccessfull!";
}
}
the problem is the database is getting updated with the previous values which was already present in the database.when i used watchpoints i found the sql statement gets loaded with the textbox values which i binded using the above database code but its not fetching the values which the user edits.
plz help.

Hey Robin,
Please check whether the code is placed under the !IsPostback condition or not.
Please bind the values under this if loop.
if(!IsPostback)
{
// Bind values
}
do this on the page load.

The values must only be bound for the first time the page is load.
In your case it seems the values to the text boxes are bound for each and every time it is loaded(even in the postback also the values are loaded.)
So, in page load you must check the condition whether the page is postback or not.
Thus add this condition while binding the values in page load.
if(!IsPostback)

Firstly check the location from where u r calling the mathod for binding values...
put it on
Page.isPostback
so it will not change the value at posting time then when u will save it the value will change
the value must be changing when u click on button and page is again loading.

Related

How to refresh dropdown list after setting index to 0?

I already have an event handler for a button that generates an excel report. (ExportExcel(filename); is the method that generates the excel report FYI) So that's fine and dandy. What I'm trying to do now is refresh the dropdown list so it reflects what the correct Dropdown selection is.
I got it to set the dropdown list to the 0th index but the dropdown list doesn't change for some reason. So I think I need to somehow individually reset the dropdown list.
Here's some code below. (I left in some comments and Debug.WriteLine()'s to show my thought process)
protected void GenerateButton1(object sender, EventArgs e)
{
// CustomerDropdown.ClearSelection();
// CustomerDropdown.Items.Clear();
// Page.Response.Redirect(Page.Request.Url.ToString(), true);
//////////
// Below is resetting the CustomerDropdown list.
ViewState["DropDownIndexSelection"] = CustomerDropdown.SelectedItem.Value.Trim();
DataSet dataSet = (DataSet)ViewState["DropDownListDs"];
var filename = "Customer ID - " + DateTime.Now + ".xlsx";
ExportExcel(filename);
// DataSet DropDownIndexSelection = (DataSet)ViewState["DropDownIndexSelection"];
CustomerDropdown.Items.Clear();
// CustomerDropdown.ClearSelection();
CustomerDropdown.DataTextField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataValueField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataSource = dataSet.Tables[0]; //assigning datasource to the dropdownlist
// CustomerDropdown.Items[0].Selected = true;
CustomerDropdown.DataBind(); //binding dropdownlist
CustomerDropdown.Items.Insert(0, new ListItem("Please select"));
CustomerDropdown.Items.Insert(1, new ListItem("All"));
CustomerDropdown.Items.FindByValue("Please select").Selected = true;
Debug.WriteLine(CustomerDropdown.Items.FindByValue("Please select").Selected == false);
Debug.WriteLine(CustomerDropdown.Items.FindByValue("Please select").Selected == true);
return;
}
How can I set the Dropdown back to "Please select" after running the ExportExcel(filename) method? I think basically what I'm asking is how do I refresh the CustomerDropdown after setting the selection to "Please select"
CustomerDropdown.SelectedIndex = 0;
after that it will select the 0th index selection, which is "Please select."
Have you tried adding to your code:
ExportExcel(filename);
// DataSet DropDownIndexSelection = (DataSet)ViewState["DropDownIndexSelection"];
CustomerDropdown.Items.Clear();
// CustomerDropdown.ClearSelection();
CustomerDropdown.DataTextField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataValueField = dataSet.Tables[0].Columns["cust_id"].ToString();
CustomerDropdown.DataSource = dataSet.Tables[0]; //assigning datasource to the dropdownlist
// CustomerDropdown.Items[0].Selected = true;
CustomerDropdown.DataBind(); //binding dropdownlist
CustomerDropdown.Items.Insert(0, new ListItem("Please select"));
CustomerDropdown.Items.Insert(1, new ListItem("All"));
CustomerDropdown.SelectedIndex=0; ---> Possible solution
?
Got from: Reference

Getting cell value from GridView after Edit button is clicked Round 2

I posted this not long ago, but no I have to update the question to ensure I get the right answer.
I have a GridView. I need to update an SQL table based on values from the GridView.
When a user clicks the default EDIT button on the GridView, changes whatever they change, then hits UPDATE. Here is where I run into problems. I've tried multiple OnRowEditing, OnRowUpdating, OnRowUpdate as the button control.
Here is the code I use to that.
protected void gvReviewedPolicy_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DateTime dateTime = DateTime.Now;
//GridViewRow editRow = gvReviewedPolicy.Rows[gvReviewedPolicy.EditIndex];
//string Emailed = editRow.Cells[7].Text;
//string UniqClient = editRow.Cells[1].Text;
//string UniqPolicy = editRow.Cells[3].Text;
string UniqClient = gvReviewedPolicy.SelectedRow.Cells[2].Text;
string UniqPolicy = gvReviewedPolicy.SelectedRow.Cells[3].Text;
//string Email = Emailed.ToString();
//string dt = dateTime.ToString();
//string Up = UniqClient.ToString();
MessageBox.Show(UniqClient);
MessageBox.Show(UniqPolicy);
//MessageBox.Show(dt);
string query = "UPDATE [Reviewed_Renewal_Policy] SET [DateUpdated] = #dateTime where ([UniqClient] = #UniqClient) AND ([UniqPolicy] = #UniqPolicy)";
using (SqlConnection conn = new SqlConnection("Data Source=GTU-BDE01;Initial Catalog=TestDB;Integrated Security=True"))
{
using (SqlCommand comm = new SqlCommand(query, conn))
{
comm.Parameters.AddWithValue("#UniqClient", UniqClient);
comm.Parameters.AddWithValue("#UniqPolicy", UniqPolicy);
//comm.Parameters.AddWithValue("#Emailed", Emailed);
comm.Parameters.AddWithValue("#dateTime", dateTime);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
}
I have some commented out because I was trying different things. However, the code that says
GridViewRow editRow = gvReviewedPolicy.Rows[gvReviewedPolicy.EditIndex];
string Emailed = editRow.Cells[7].Text;
string UniqClient = editRow.Cells[1].Text;
string UniqPolicy = editRow.Cells[3].Text;
It's supposed to access the values in those cells when UPDATE button is pushed. However, using MessageBox.Show , comes back blank.
Anyone have any idea how I can capture those values after hitting Edit, then the default UPDATE button?
I've tried to make that Winforms Datagrid usable for "write through" in the past, by implementing an DataGridView subclass (this allows you to access everything) but since immutable databases and queue transactions came into view, my Access-flavour DataGrid did not survive modern paradigm. Nowadays I tend to support ASP.NET MVC 5 to "edit" databases.
Anyway have you considered to connect a DataSource ? You don't have to access cells.. you can update using a connection like
private SqlDataAdapter daGrid = new SqlDataAdapter();
and this type of approach, you will have to fill in the details yourself, the complete code consists of several classes and is too large to post,
protected void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
/// .. perform actions according to keyboard events ..
/// .. for example below one ..
}
public override void UpdateAfterEditGrid(DataSet ds, DataGridView dataGridView1, bool DoRestoreCursor)
{
if (daGrid != null)
{
if (conn.State == ConnectionState.Closed) conn.Open();
dataGridView1.EndEdit();
try
{
if (ds == null)
{
//DataGridView dgv = dataGridView1;
//Console.WriteLine("Go datasource update .. " + dgv[cColumnIndex, cRowIndex].Value);
daGrid.Update((DataTable)dataGridView1.DataSource);
}
else daGrid.Update(ds);
LoadGridRestoreCursor(dataGridView1, DoRestoreCursor);
}
catch { ErrorReporting.ErrorMessage("== cannot update this content =="); }
}
}

Data set Not referencing correctly

I'm having a problem with data set. I'm using one to populate text boxes of my form. The user selects a value to search from, they press a button and then the text boxes are populated. This works fine for the first record but I want to page through them. I've declared a data set to be used by my other methods but when it gets to paging the returned rows I keep getting an Object reference error. Can anyone shed some light on where I'm going wrong?
Declaring Variables:
//creates a global dataset for the copies table
DataSet dataSetHM;
//create default row values
int MaxRows = 0;
int inc = 0;
The connection to the database and filling the data set:
protected void ExecuteSelectCopies(string sName)
{
SqlConnection connection = new SqlConnection(GetConnectionString());
string sql =
"SELECT tblCopies.CopyID, tblSoftware.SoftwareName, tblCopies.AssetName, tblCopies.Location,"
+ " tblCopies.LicenceKey, tblCopies.OEM, tblCopies.State, tblCopies.InstallationDate"
+ " FROM tblCopies"
+ " INNER JOIN tblSoftware ON tblCopies.SoftwareID = tblSoftware.SoftwareID"
+ " WHERE tblSoftware.SoftwareName = #SoftwareName"
+ " ORDER BY tblCopies.CopyID";
SqlDataAdapter adapterHM = new SqlDataAdapter();
SqlCommand select = new SqlCommand(sql, connectionHM);
adapter.SelectCommand = select;
select.Parameters.Add(new SqlParameter("#SoftwareName", sName));
//open the connection
connectionHM.Open();
dataSetHM = new DataSet();
adapterHM.Fill(dataSetHM, "Copies");
NavigateCopies();
MaxRows = dataSetHM.Tables["Copies"].Rows.Count;
connectionHM.Close();
}
The method for filling the text boxes:
private void NavigateCopies()
{
DataRow dRow = dataSetHM.Tables["Copies"].Rows[inc];
TextBoxCopyID.Text = dRow.ItemArray.GetValue(0).ToString();
TextBoxSoftwareName.Text = dRow.ItemArray.GetValue(1).ToString();
DropDownListAssetName.SelectedItem.Text = dRow.ItemArray.GetValue(2).ToString();
DropDownListLocation.SelectedItem.Text = dRow.ItemArray.GetValue(3).ToString();
TextBoxLicence.Text = dRow.ItemArray.GetValue(4).ToString();
DropDownListType.SelectedItem.Text = dRow.ItemArray.GetValue(5).ToString();
DropDownListState.SelectedItem.Text = dRow.ItemArray.GetValue(6).ToString();
TextBoxInstall.Text = dRow.ItemArray.GetValue(7).ToString();
}
And finally the button for the next record:
protected void ButtonNext_Click(object sender, EventArgs e)
{
if (inc != MaxRows - 1)
{
inc++;
NavigateCopies();
}
else
{
MessageBox.show("No more Rows");
}
}
Any help with this would be very much appreciated. I honestly can't understand why the data set works for the navigation method initially but not for the second. I've been using this http://www.homeandlearn.co.uk/csharp/csharp_s12p7.html as a guide, their example displays data on page load where as mine is displayed when a search parameter is selected. I don't know if this is a problem but a bit more information never hurts!
Persist the DataSet in the Session/Cache/ViewState (which ever one of these is the most applicable solution for you).
That way you can retrieve the DataSet between postback's and continue to display the data that is required.
Here is how to accomplish this (albeit a simple example) and an article that delves into object persistence within asp.net: asp.net object persistence.

how to send value of query string in an array

I am making a Crystal-Report from data of GridView. The GridView has three columns in which two columns are filled with values coming from DataBase in a label and third column has a CheckBox which on check sends the value of these two columns as query string to the .cs page of Crystal-Report. The column value is used by the stored-procedure and then result is shown in the Crystal-Report.
Now my problem is if user checks two CheckBox then the value of both columns should be sent to Crystal-Report page as array. How to implement this
My code behind in GridView page is
protected void ChkCity_CheckedChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gdCityDetail.Rows)
{
bool ischecked = ((System.Web.UI.WebControls.CheckBox)row.Cells[0].FindControl("CheckBox2")).Checked;
if (ischecked == true)
{
int getrow = Convert.ToInt32(e.CommandArgument);
Label label1 = (Label )gdVilDetail.Rows[getrow].FindControl("label1");
Label label2= (Label )gdVilDetail.Rows[getrow].FindControl("label2");
Response.Redirect("~/crystal report/Landowner.aspx?Yojna=" + label1.text + "&Village=" + label2.text);
}
and the code on .cs page of Crystal-Report is
private void cityreport()
{
SqlCommand Cmd = new SqlCommand("Showvillage", Constr1);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#Yojna_No", Request.QueryString[0]);
Cmd.Parameters.Add("#Village_Code", Request.QueryString[1]);
DataSet ds = new DataSet();
I think you cannot pass Array or any other Objects through Query string except string values. Rather you can use Session Variable.
Try this..
In page One.
//Set
Session["Variable"] = ArrayObj;
In page Two.
//If String[]
string[] arry = (string[])Session["Variable"];
hope it helps..
Check this link. There is a code in the link which has used array to send the value with querystring. I hvn't tried that but may be that will work too.
http://www.codeproject.com/Questions/298718/array-in-query-string

How to avoid instantiation of variable after button click?

I am running a Sql query whose where clause changes everytime when button click occurs.
Now the where clause consists of an index to the list. When the button click happens ,page load occurs which causes the index value intialisation.
int i=0;
protected void Button1_Click(object sender, EventArgs e)
{
string str = lst1.ElementAt<string>(i++);
qr = "Select BdId,First_Name,Last_Name,Age,Gender,Relationship_status,Birthday from [User] where BdId='" + str + "'";
da2 = new SqlDataAdapter(qr, con);
da2.Fill(ds2);
Label1.Text = Label1.Text + " " + i.ToString();
}
How can I avoid this happening? I want index value to be global so that it doesn't instantiate again every time button click occurs.
Thanks
Every time there is a request for your page, a new instance of that page-class is created to handle that request. So any fields are re-initialized.
You can store a value in ViewState to remember a value over various requests:
private int TheIndex
{
set { ViewState["TheIndex"] = value; }
get
{
if (ViewState["TheIndex"] == null)
return 0;
return (int)ViewState["TheIndex"];
}
}
And use TheIndex instead of i.
EDIT
Plus, as CodeInChaos notes, use a more descriptive name. That will help in understanding the code if someone else (or you yourself in a few months) needs to maintain this code.
You can store the variable in Session object provided by ASP.Net. You can check this tutorial also.
if(Session["CurrentIndex"] != null) i = (int) Session["CurrentIndex"];
else Session["CurrentIndex"] = i;
Hope this works for you.

Categories