ASP.NET: TextBox.Text doesn't have updated value - asp.net

I have an initialize function that loads data into my textbox NameTextBox, and then I add an "s" to the name. I then click the Save button that executes SaveButton_Click when debugging the value for NameTextBox.Text is still the original string (FirstName) and not (FirstNames). Why is this? Thanks.
Edit: Sorry here you go let me know if you need more...
Page_Load(sender, e)
Info = GetMyInfo()
Initialize()
Initialize()
NameTextBox.Text = Info.Name
SaveButton_Click(sender, e)
Dim command As SqlCommand
command = GetSQLCommand("StoredProcedure")
command.Parameters.AddWithValue("#Paramter", NameTextBox.Text)
ExecuteSQLCommand(command)

If the textbox is disabled it will not be persisted back to the codebehind, also if you set the initial value everytime (regardless of IsPostBack) you are essentially over writing what the value is when it gets to the Event handler (SaveButton_Click). Ex:
page_load() { NameTextBox.Text = "someValue";}
....
saveButton_Click() { string x = NameTextBox.Text;}
The above code will always have the text value of the textbox be "someValue". You would need to wrap it in an if(!IsPostBack) like so....
page_load() { if(!IsPostBack) {NameTextBox.Text = "someValue";}}
....
saveButton_Click() { string x = NameTextBox.Text;}

Related

Gridview selected value always returns 0?

I am trying to delete a row from a gridview if "Web drop course" option is selected. Here is the UI:
And the code:
for (int i = 0; i < showCourses.Rows.Count; i++)
{
if (((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue == "1")
{
dropList.Add(showCourses.Rows[i].Cells[2].Text +showCourses.Rows[i].Cells[3].Text );
}
}
Here is the dropdown list:
<asp:ListItem Selected="True" Value="0">No Action</asp:ListItem>
<asp:ListItem Value="1">Web Drop Course</asp:ListItem>
The problem is, ((DropDownList)showCourses.Rows[i].FindControl("actionmenu")).SelectedValue always returns 0 whether I choose No action or Web drop course. Can anyone see the problem?
Thanks
You are most likely not protecting against rebinding your data on postback. When your event that causes postback fires, the page load event fires before this. If you are binding in page load without a check for postback, you are basically resetting your data and then going into your event handler.
The page life cycle might be a good read: Page Life Cycle
Considering your previous post, you are rebinding the gridview on each postback. Wrap those lines with a !IsPostback conditional. Better wrap those into a method (say PopulateGrid()) and call it. Then, you can re-call that method in other situations where you might need to rebind the data (OnPageIndexChanged for example). Change your Page_Load method like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
PopulateGrid();
}
}
private void PopulateGrid()
{
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = Userfunctions.GetConnectionString();
con.Open();
string query = "select * from RegisterTable where StudentID='" + MyGlobals.currentID + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
showCourses.DataSource = tab;
showCourses.DataBind();
}
}

Object reference not set to an instance of an object. This happens while adding checkboxlist control dynamically

Object reference not set to an instance of an object.
protected void cmdSave_Click(object sender, EventArgs e)
{
string strNames = string.Empty;
CheckBoxList Chkboxx = (CheckBoxList)PlaceHolder1.FindControl("Chkbox");
foreach (ListItem em in Chkboxx.Items) //-------- (Showing error)
{
if (em.Selected)
{
strNames += em.Value + ", ";
}
}
string final_name = strNames.Substring(0, strNames.Length - 2);
lblNames.Text = final_name;
}
Actually I am adding Checkbox control dynamically :
protected void ddl_varient_SelectedIndexChanged1(object sender, EventArgs e)
{
string query = "select prd_vrtyvalue_id,varient_value from tbl_ProductVariety_Value where varient='" + ddl_varient.SelectedItem.Text + "' " +
" order by varient_value asc ";
DataTable abc = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(query, new CommonClass().connection());
ada.Fill(abc);
ChkboxList.ID = "Chkbox";
for (int i = 0; i < abc.Rows.Count; i++)
{
ChkboxList.Items.Add(new ListItem(abc.Rows[i]["varient_value"].ToString(), abc.Rows[i]["prd_vrtyvalue_id"].ToString()));
}
ChkboxList.RepeatColumns = 2;
PlaceHolder1.Controls.Add(ChkboxList);
}
Can Anybody tell me, what exactly i am doing wrong !
The way ASP.NET WebForms work is that the entire page is re-built during each post back. So, I imagine this is what is occuring:
Page gets "built" and includes only controls defined within your ASCX/ASPX file.
User clicks on DDL_VARIENT checkbox and the ChkboxList is added to PlaceHolder1
Form is rendered back to the user so they can see ChkboxList
Save button is clicked, causing another postback.
Page is re-built, setting all the controls back to what is defined within your ASPX/ASCX code. This does not include ChkboxList.
Your code is hit, ChkboxList no longer exists and you get your problem.
To fix, you could re-add your ChkboxList on Page_Load depending on the value of your DDL_VARIENT checkbox. If I were you though, I'd be tempted to define the ChkboxList within your ASPX/ASCX code and then set the visibility of the list depending on the value of the DDL_VARIENT checkbox within Page_Load.
I should add, the entire of the above is dependant upon you using ASP.NET WebForms. If you're using MVC then it's probably wrong.

Retain textbox values on page refresh

I have a textbox in a user control uc1. I have embedded this uc1 in a page called default.aspx. My issue is after running the application and entering some data in the textbox, when refresh the page i would like to show the values that i have entered in the textbox and not clear the textbox. I would like help with code on how to achive this. Thanks in advance for your help.
Create a global variable at the top of your aspx.cs page:
public string textboxValue
{
get
{
if (ViewState["textboxValue"] != null)
return ViewState["textboxValue"].toString();
else
return "";
}
set
{
ViewState["textboxValue"] = value;
}
}
Then, in PageLoad(), assign textboxValue a value:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
textboxValue = MyTextBox.Value;
else
MyTextBox.Value = textboxValue;
}
You can also use textboxValue to assign the value of MyTextBox at any time, or use it in any other way that might be useful to you.
The default behavior for all asp.net server side controls (runat="server") is to maintain their state. If your textbox is being cleared when your page refreshes, you are likely clearing that value yourself in code.
Are you dynamically adding the textbox or user control? If so, are you doing that during PageInit? Adding them later may cause them to lose state.
I was able to refresh the page without clearing the value in textbox. I did it as below:
I created a public property in the UC1.vb as below:
Public Property textbox_value() As String
Get
If Session("textbox1") IsNot Nothing Then
Return Session("textbox1").ToString()
Else
Return ""
End If
End Get
Set(value As String)
Session("textbox1") = value
End Set
End Property
And in the page_load event of the user control i added the code below:
If IsPostBack Then
textbox_value= textbox1.Text
ElseIf Not IsPostBack Then ' First time the page is loaded or when the page is refreshed
textbox1.Text = textbox_value
End If
Hope it helps.

ReportViewer.Find not working

I have a textbox, and a link button. On the same page I have a reportviewer.
The reportviewer is in updatepanel with linkbutton as async postback trigger.
I'm trying to find string (entered in textbox) in the report; when linkbutton is hit.
protected void lbtnFind_Click(object sender, EventArgs e)
{
ReportViewer1.Find(txtSearch.Text.Trim(), 1);
}
But that line gives error: Some parameters or credentials have not been specified Please help.
If txtSearch is a control you added, it will not be inside ReportViewer1.
If txtSearch is a control inside your ContentTemplate you should be searching in that control as follows:
var txtSrch = (TextBox)myUpdatePanel.ContentTemplate.Controls.FindControl("txtSearch");
You can get the text value from there and then set the parameters for the ReportViewer1 and refresh it.
ReportParameter[] parameters = new ReportParameter[1];
parameters[0] = new ReportParameter("Search", txtSrch.Text);
ReportViewer1.LocalReport.SetParameters(parameters);
ReportViewer1.RefreshReport();

How can I use a page_load local variable in event handler of a button

Im making a site in Visual Studio using vb and I have a variable in page_load but need its value in the event handler of a button for passing on session.
Any suggestions on how I can do this? Any help is appreciated
You can store a value in the CommandArgument property of a Button:
btn.CommandArgument = "Your value"
And then when handling the event you can pull it out:
CType(sender, Button).CommandArgument
You could also make a new class that extends Button and create new properties like below if you need multiple arguments:
Class SessionButton
Inherits Button
Public Property SessionGUID() As Guid
Get
Dim s As Guid = Nothing
If Not String.IsNullOrEmpty(ViewState("SessionGUID")) Then
s = New Guid(ViewState("SessionGUID").ToString())
End If
Return s
End Get
Set(ByVal value As Guid)
ViewState("SessionGUID") = value.ToString()
End Set
End Property
End Class
couldn't you just make the variable a class scoped variable, instead of local?
You can store it in a viewstate backed property:
Public Property MyStringVar() As String
Get
If ViewState("MyStringVar") = Nothing Then
Return String.Empty
End If
Return ViewState("MyStringVar").ToString()
End Get
Set
ViewState("MyStringVar") = value
End Set
End Property
Now using this property you can save your variable on page load and access it in the button click event handler.
EDIT: updated to VB
you declare the variable outside the page_load and then you can use it where you want :)
You could also create a class that encapsulates the action. Then you can capture any data you want and easily add to it later.
void Page_Load()
{
myBtn.Click += new MyButtonClass(variable).Run;
}
class MyButtonClass
{
int Param;
MyButtonClass(int param)
{
Param = param;
}
public void Run(object sender, EventArgs args)
{
// Do something usefull
}
}
If the data is created/retrieved on every Page_Load, this will work. If it is wrapped around an (! IsPostBack), the data must be stored in a session. Fortunatly, the class can be easily modified to store/load the variable from a session parameter.
I'm sorry for the c# code, maybe someone else can translate it then remove this message?

Resources