How to retrieve text from text box after postback? - c#

I have some textbox's who's values are all empty when i try retrieve there values from the behind code after a post back submit.
My submit button:
<ICCM:ICCMImageButton ID="btnSubmit" runat="server" meta:resourcekey="btnResSubmit" onclick="btnSubmit_Click" PostBack="true" style="float:right; padding-right:5px;" TabIndex="23"/>
Behind C# code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
//code
objCmd.Parameters.Add("#FirstName", SqlDbType.NVarChar, 50).Value = txtFName.Text.ToString();
//more code
}
Page load:
btnSubmit.ClickScript = "if(ValidatePage() == false){return false}; this.disabled = true; document.getElementById(this.getAttribute('ControlID') + 'Text').innerHTML = '" + Resources.ICCMCPortal.Submitting + "';";
OnInt:
btnSubmit.Page = this.Page;
The text value is always "" unless i pre populated the textbox in the page load then the text will be that regardless if i made a change to it.

Set you textbox values inside here:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SetTextboxValues();
}
}
This way the wont be reset on postback.

Related

Setting nested control values in a asp:formview from C# code behind

I was approaching this from the angle of controlling the asp:SqlDataSource bound to the controls inside the formview that is part of this topic and was getting no where rather fast, so I opt'd to close that thread and approach this at the control level inside the formview instead as it seemed to make a lot more sense to me.
So for back ground The code below is intended to inject string values listed in the first two lines of the screen clip below (and the two corresponding Response.Write's at the bottom of the included code block).
What I am trying to do, is use FindControl to set the Text value in the case of these items (but I have a few asp:checkbox's to deal with after getting this done as well that will need the same treatment.) and for now I'm just focusing on these two controls. The first is a asp:label
<asp:Label runat="server" ID="SubmitByLbl" Text='<%# Eval("SubmitBy") %>' ></asp:Label>
The next is a asp:TextBox:
<asp:TextBox Text='<%# Bind("SubmitDT") %>' runat="server" ID="SubmitDTTextBox" />
Both of these are sitting inside of the asp:FormView with an ID="AddItemFv" which has a DataSourceID="AddInvAsset" (which is irrelevant for this discussion but just provided as supplemental info).
Here is the code behind where my problem is:
namespace CInTrac
{
public partial class AddAsset : System.Web.UI.Page
{
protected void Page_Preload(object sender,EventArgs e)
{
AddInvAsset.SelectParameters.Add("SubmitBy", Session["RegUser"].ToString());
AddInvAsset.SelectParameters.Add("SubmitDT", DateTime.Now.ToString("MM/dd/yyyy"));
}
protected void Page_Load(object sender, EventArgs e)
{
Label uname = (Label)AddItemFv.Row.FindControl("SubmitBy");
if (uname != null)
uname.Text = Session["RegUser"].ToString();
TextBox udate = (TextBox)AddItemFv.Row.FindControl("SubmitDT");
if (udate != null)
udate.Text = DateTime.Now.ToString();
Response.Write("<b>Submitted by should be:</b> = " + Session["RegUser"].ToString() + "<br>");
Response.Write("<b>Submit Date should be:</b> = " + DateTime.Now.ToString("MM/dd/yyyy") + "<br>");
}
}
}
The problem that I'm having is Just what you see in the example above; absolutely nothing! I'm new to C# so I am likely doing something wrong with my code here and in debug my trace indicates that as we check for null it then fails to assign value to .Text of each VAR and therefore our values never show up.
Update:
As IM pointed out I had missed the proper name of the controls in the code. Below are the corrections I made to the code above which works fine. Again THanks to Inquisitive_mind for pointing out my error. :
protected void Page_Load(object sender, EventArgs e)
{
Label uname = (Label)AddItemFv.Row.FindControl("SubmitByLbl");
if (uname != null)
uname.Text = Session["RegUser"].ToString();
TextBox udate = (TextBox)AddItemFv.Row.FindControl("SubmitDTTextBox");
if (udate != null)
udate.Text = DateTime.Now.ToString("MM/dd/yyyy");
}
The ID of the controls is incorrect
Change
Label uname = (Label)AddItemFv.Row.FindControl("SubmitBy");
TextBox udate = (TextBox)AddItemFv.Row.FindControl("SubmitDT");
To
Label uname = (Label)AddItemFv.Row.FindControl("SubmitByLbl");
TextBox udate = (TextBox)AddItemFv.Row.FindControl("SubmitDTTextBox");
EDIT
You will have to move the FindControl to a FormView event.The controls will only be accessible after the FormView has been completely created and databound.Try moving the code from page_load to YourFormView_Databound event.
protected void YourFormView_DataBound(Object sender, EventArgs e)
{
Label uname = (Label)AddItemFv.Row.FindControl("SubmitByLbl");
if (uname != null)
uname.Text = Session["RegUser"].ToString();
TextBox udate = (TextBox)AddItemFv.Row.FindControl("SubmitDTTextBox");
if (udate != null)
udate.Text = DateTime.Now.ToString();
}

How to save option selected in Dropdownlist after selection

I am displaying columns in a GridView and one of the columns is a dropdownlist. I want to be able to save the option selected in the dropdownlist as soon as something is selected. I have done this with one of the columns that has a textbox so I was hoping to do something similar with the DropDownList.
The code for the textbox and dropdownlist:
protected void gvPieceDetails_ItemDataBound(object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
JobPieceSerialNo SerNo = e.Row.DataItem as JobPieceSerialNo;
if (SerNo != null) {
TextBox txtComment = e.Row.FindControl("txtComment") as TextBox;
txtComment.Text = SerNo.Comment;
txtComment.Attributes.Add("onblur", "UpdateSerialComment(" + SerNo.ID.ToString() + ", this.value);");
DropDownList ddlReasons = (e.Row.FindControl("ddlReasons") as DropDownList);
DataSet dsReasons = DataUtils.GetUnapprovedReasons(Company.Current.CompanyID, "", true, "DBRIEF");
ddlReasons.DataSource = dsReasons;
ddlReasons.DataTextField = "Description";
ddlReasons.DataValueField = "Description";
ddlReasons.DataBind();
ddlReasons.Items.Insert(0, new ListItem("Reason"));
}
}
How to I create an update function for a dropdownlist?
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = ddlReasons.SelectedValue.ToString();
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; //can't find sel value
SerNo.Update();
}
Dropdownlist:
<asp:DropDownList ID="ddlReasons" runat="server" OnSelectedIndexChanged="DDLReasons_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
I created an OnSelectedIndexChanged function to get the selected value. But how do I then save that value? Is there a way to pass it into the UpdateSerialReason function?
Just move the string sel declaration outside the scope of DDLReasons_SelectedIndexChanged and get the Text of the SelectedItem since it's included in your data source.
private string sel;
protected void DDLReasons_SelectedIndexChanged(object sender, EventArgs e)
{
sel = ddlReasons.SelectedItem.Text;
}
public static void UpdateSerialReason(int SerNoID, string Reasons)
{
JobPieceSerialNo SerNo = new JobPieceSerialNo(SerNoID);
SerNo.Reason = sel; // Should now be available
SerNo.Update();
}
The way you had it previously it was only available in the local scope, i.e, inside the method in which it was being declared and used.
You can get selected value when you call your function:
UpdateSerialReason(/*Some SerNoID*/ 123456, ddlReasons.SelectedValue)
You will lose your value after postback is done if you save value to variable as Equalsk suggested. If you need to use your value on the other page you can save it in session.
If you are working within one asp.net page you can do as I suggested above. Then you can skip the postback on your DropDownList and call UpdateSerialReason when you need :)
And you might want to add property ViewStateMode="Enabled" and EnableViewState="true"

Label Text Not Showing Outside of Page_Load

I have a Grid and on top of the grid, I like am showing a label as such:
<asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>
On delete of a row in my grid I have the following code:
protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
{
if (!(User.IsInRole("Administrator")))
{
lblMsg.Text = "Must be an Admin in delete.";
return;
}
NOTE: The debugger does go to where I have the label text displayed but it simply does not display on the page. :
lblMsg.Text = "Must be an Admin in delete.";
NOTE: If I have the same code in the page load, the label text shows up fine on the page Also DO NOT have (!IsPostBack){} in my code.
Therein lies your issue. When your page is posting back the label is getting assigned the value:
lblMsg.Text = "Must be an Admin in delete.";
But Page_Load gets called again. So your Page_Load should look like this
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
//Populate my page
}
}
This will hold true for almost every page you write in ASP.NET

Select and show selected row to label

So, when I click Select I want to show in a Label all datas that contain one row. I have managed to make this, except DropdownList. When I click "Select" it's just empty.
protected void GridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
Label1.Text = GridView1.Rows[e.NewSelectedIndex].Cells[1].Text;
Label2.Text = GridView1.Rows[e.NewSelectedIndex].Cells[2].Text;
Label3.Text = GridView1.Rows[e.NewSelectedIndex].Cells[3].Text;
}
P.S.: I have not done this programmatically. The only code I've wrote on .aspx.cs file is the code above.
Use this to find the value. its not showing the value because of template field control.
I have used the gridview control that you pasted in pastebin.
protected void GridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e) {
Label drpValue =
(Label)this.GridView1.Rows[e.NewSelectedIndex].Cells[1].FindControl("Label1");
Lbl1.Text = drpValue.Text;
Lbl2.Text = GridView1.Rows[e.NewSelectedIndex].Cells[2].Text;
Lbl3.Text = GridView1.Rows[e.NewSelectedIndex].Cells[3].Text;
}

Show dropdown selected value in the grid on the same page

I have a drop down which has the list of delegates. When the user selects a delegate then I populate the available meet-timings in the second dropdown using the selectedindexchange event of the 1st dropdown
Aspx page
<asp:DropDownList ID="delegate_ddl" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddldelegates_SelectedIndexChanged" Width="200px"></asp:DropDownList>
<asp:DropDownList ID="delegatetime_ddl" runat="server" Width="90px"></asp:DropDownList>
<asp:Button ID="adddelegate" runat="server" Text="Add" onclick="adddelegate_Click"/>
.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds1 = getdata.getdelegatelist();
delegate_ddl.DataSource = ds1.Tables[0];
delegate_ddl.DataTextField = "DELEGATE_NAME";
delegate_ddl.DataValueField = "DELEGATE_ID";
delegate_ddl.DataBind();
delegate_ddl.Items.Insert(0, "--Select--");
}
}
protected void ddldelegates_SelectedIndexChanged(object sender, EventArgs e)
{
string delselection = delegate_ddl.SelectedValue.ToString();
DataSet ds2 = getdata.getdelegatetimelist(delselection);
if (ds2.Tables[0].Rows.Count > 0)
{
delegatetime_ddl.DataSource = ds2.Tables[0];
delegatetime_ddl.DataTextField = "TIMESLOT";
delegatetime_ddl.DataValueField = "TIMEID";
delegatetime_ddl.DataBind();
}
else
{
time_lbl.Text = "No slots Open";
}
}
protected void adddelegate_Click(object sender, EventArgs e)
{
string delegateselected = delegate_ddl.SelectedValue.ToString();
string timeslotselected = delegatetime_ddl.SelectedValue.ToString();
getdata.delegatemeetinsert(personidd, delegateselected, timeslotselected);
}
Now the data gets inserted – but my question here is
As soon as the user click add button I would like to display the delegate selected and the time slot selected in a some sort of a grid view or dynamic table below with a delete option.
Can someone please provide a code sample in C# to achieve the above
Instead of using Gridview for displaying data use some basic control like Labels,it will reduce lot's of unncessary code. use Asp.net 'Panel' control and encapsulate all label and button(for delete purpose) into Panel then hide/show according to need. here is the outline of code that might help you,
if(!page.IsPostBack) // This goes into Page_Load
{
Panel1.Visible=false;
}
protected void adddelegate_Click(object sender, EventArgs e) // add this additional code
{
Panel.Visible=True;
GetDelegate()// This method retrieve the delegate you inserted..
Lable1.Text= "Set here Delegate name you just Retrieved"
Label2.Text="Delegate time you retrived"
}
protected void BtnRemovedelegate_Click(object sender, EventArgs e)
{
string Personidd= retrieve person id
string delegateName= Lable1.text;
String timeslot=Label2.Text
SomeDeleteMethod(personidd, delegateName, timeslot);
Panel1.Visible=false;
}
Hope you get the idea..

Categories

Resources