How to avoid instantiation of variable after button click? - c#

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.

Related

Is SqlCommand the only way of adding,deleting and updating records?

I am currently creating a Windows Forms application that has 4 buttons, an Update, Add, Delete and Cancel button. My information that I have within my records goes directly into my textboxes, and I have used a SqlCommand cmd;.
I have added this in my Add button click handler:
private void btnAdd_Click(object sender, EventArgs e)
{
if (true)
{
Utilities.ResetAllControls(this);
connection.Open();
cmd = new SqlCommand("insert into tblCar values('" + txtbxVehicleRegistrationNumber.Text + "','" + txtbxMake.Text + "','" + txtbxEngineSize.Text + "','" + txtbxDateRegistered + "','" + txtbxRentalPerDay + "','" + CbxAvailable.Checked + "')", connection);
MessageBox.Show("Your information has been successfully added.");
connection.Close();
}
}
The Utilities listed is a class that I have created. Is this the right way that I am going about adding data? Also I want to know how (upon clicking the Add button) clears all existing data for me from the textboxes (but not deleting them) to add new ones. I'd appreciate if someone helps me with this predicament of mine.
The Utilities class is:
public class Utilities
{
public static void ResetAllControls(Control form)
{
foreach (Control control in form.Controls)
{
if (control is TextBox)
{
TextBox textBox = (TextBox)control;
textBox.Text = null;
}
if (control is ComboBox)
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
}
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
checkBox.Checked = false;
}
if (control is ListBox)
{
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
}
}
}
}
Your code seems fine to me, and I am unsure as to what your exact issue is; however, to clear your TextBox control's .Text property; assign it a value of string.Empty.
textBox1.Text = string.Empty;
As far as your insert command, that looks fine. A point has been made that your code is vulnerable to SQL Injection, but unless you need to safeguard your information, then I wouldn't worry too much. If you are worried about SQL Injection and how to protect against it, there are many posts here, and many articles online on how to protect your applications from this type of attack. Things to look into are:
Parameterization of dynamic data and queries.
Don't overuse dynamically generated queries.
Utilize sp_executesql when executing dynamic queries so that parameters can't be manipulated.

Gridview rebind data with new parameters

OK, so I need to change the values stored in my gridview based on input from user.
I used to filter it 100% with javascript, but it turns out that it needs to be paged, so that wont work. Instead, I have to call on the datasource again, but with parameters from the textbox.
I've figured out that I must call a function in code behind and from there call DataBind(), but I dont even know where to start. Please help
I know that I ought to post some code to show that I've made an effort, but I really dont have anything to show. i guess it would be something along these lines?:
protected void ReBind(string sParameter)
{
SqlDataSource.SelectParameters.Add("parameterName", sParameter);
myGridView.DataBind();
}
But obviously I'm fumbling in the dark here.
Take a update button
Write method for update function
public int update_method(string ParameterName)
{
module c = new module();
c.DB_Connection();
int i;
string QRY = "UPDATE TableName SET Parameter_Name='" + ParameterName + "' WHERE Parameter_Name='" + ParameterName + "'";
SqlCommand CMD = new SqlCommand(QRY, c.con);
i = CMD.ExecuteNonQuery();
return i;
}
on button click
protected void ButtonUpdate_Click1(object sender, EventArgs e)
{
update_method(ParameterNametxt.Text);
}
update_method(farm, common_obj);
Turns out that this worked out fine:
protected void ReBind(String sParameter)
{
SqlDataSource.SelectParameters.Remove(SqlDataSource.SelectParameters["parameterName"]);
SqlDataSource.SelectParameters.Add("parameterName", sParameter);
myGridView.DataBind();
}

textbox value remains unchanged on form submission in edit profile page

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.

How do i reset values of dynamically created controls on ASP .NET c# page?

i have an array of buttons added to a panel control and need to reset them to their original values, is this possible pragmatically?
protected void Page_Load(object sender, EventArgs e)
{
RenderTable();
}
private void RenderTable()
{
Button[] board = new Button[9];
for(int i =0; i <board.Length; i++)
{
board[i] = new Button();
board[i].Text = " ";
board[i].Width= board[i].Height = 50;
board[i].Click += PlayerClick;
board[i].ID = "pos" + i;
Panel1.Controls.Add(board[i]);
}
}
You will need to store the values yourself in session, viewstate, or simply look in the post values for them. You're already using a custom ID so use those values if you use the form post method.
You should be able to store an array of the original values as well, and loop through reassigning them.
panel.Controls.Clear() ?

Problems submitting dynamic checkbox values

I'm working on creating a dynamic list of checklists and came to the below implementation. I have been trying for a week now to get the fnameID text values on the submit button click to send the values into the database. I do not want to use the postback oncheckedchanged.on each check because the checklist is over 1000 rows long and each postback/reload wastes too many resources. I just want to be able to use some method to be able to grab the checked values so I can insert them into the database on the submit button "Click Me!" click.
I googled and found the FindControl method but i still am not able to grab the fnameID values. I either get a undefined or it errors out on me. Any help would be greatly appreciated! Thanks!
aspx:
<div id="aGAccountabilityCheckListBox">
"Panel1" runat="server">
<asp:LinkButton ID="LinkButton1" Width="66px" runat="server" onclick="LinkButton1_Click">
Click Me!
</asp:LinkButton>
code behind:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
CheckBox _checkbox = new CheckBox();
_checkbox.ID = "dynamicCheckListBox" + Convert.ToString(i);
Panel1.Controls.Add(_checkbox);
Panel1.Controls.Add(" <span id='fnameID" + i + "' >test" + i + "</span>");
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["cnDatabase"].ToString());
SqlCommand cmd = new SqlCommand("usp_CreateUser", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Thanks!
State is restored to controls before the load event runs. If your controls don't already exist by then, they'll lose their state and you won't know they were checked. Create your checkboxes in the Init or PreInit event instead.
move the checkbox creation to the CreateChildControls page method
to retrieve checkbox state in the LinkButton1_Click handler you can use the following code
for (int i = 0; i < 50; i++)
{
string cbxId = string.Format("dynamicCheckListBox{0}", i);
CheckBox _checkbox = Panel1.FindControl(cbxId) as CheckBox;
if (_checkbox == null )
continue;
if ( _checkbox.Checked )
//do something
}
Your fnameID's are spans created as a literal control. There is no post back value you are going to get if you set it up that way. It's just arbitrary html or text from the asp.net perspective.
Why are you not using the Text property for CheckBox?

Categories