Get text/value from textbox after value/text changed server side - c#

I have a FormView with data(DataSource,DataBind) that I fill with value='<%# Eval("Name") %>' , but after I'm changing the text in TextBox and press update button I see the same value that before, I cant see new value that I have typed.
What I am missing here?
my html
<asp:FormView ID="MainFormTemplate" runat="server">
<ItemTemplate>
<li class="li_result" runat="server">
<div class="col-3">
<input id="txt_Name" runat="server" value='<%# Eval("Name") %>'>
</div>
</li>
</ItemTemplate>
</asp:FormView>
<asp:Button id="btn_Update" runat="server" OnClick="btn_Update_Click" Text="Update" />
Server side
protected void Page_Load(object sender, EventArgs e)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
public void btn_Update_Click(object sender, EventArgs e)
{
//using System.Web.UI.HtmlControls
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;//i see old value ,not new one that i typed in text box
}

In every postback, you are always getting the old value from your database. The solution is check if the page is being rendered for the first time (!IsPostBack) then set your MainFormTemplate's DataSource else if is being loaded in response to a postback (IsPostBack) get the txt_Name's value like this:
HtmlInputText twt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
using (DB_MikaDataContext data = new DB_MikaDataContext())
{
MainFormTemplate.DataSource = data.File_Projects.Where(x => x.Num_Tik.Equals("12")).ToList();
MainFormTemplate.DataBind();
}
}
else
{
twt = MainFormTemplate.FindControl("txt_Name") as HtmlInputText;
}
}
protected void btn_Update_OnClick(object sender, EventArgs e)
{
string text = twt.Value; // You will get the new value
}

with Page_Load executing every postback, you are always writing value from database (?), and value sent from browser is lost (although still exist in Page.Request.Form member).

In ASP.NET, When a page is submitted, the Page_Load event runs before the button click event. So, the textbox value gets repopulated with its original value before the click event looks at that value.
If this is the situation, then you can wrap the code that assigns the value to the textbox in an if block like this:
if (!IsPostBack)
{
HtmlInputText twt = (HtmlInputText)MainFormTemplate.FindControl("txt_Name");
string text = twt.Value;
}
Hope this helps you.

Related

(ASP.NET )Store currently selected Asp:Listbox item as string

I am trying to store the text of the currently selected item of an Asp:Listbox in a variable. The value is always stored a null, or I receive the error
"System.NullReferenceException: 'Object reference not set to an instance of an object.'"
Listbox declaration below
<asp:ListBox ID="lbModules" runat="server" AutoPostBack="true" OnSelectedIndexChanged="lbModules_SelectedIndexChanged" ></asp:ListBox>
Code for SelectedIndexChanged below
`
protected void lbModules_SelectedIndexChanged(object sender, EventArgs e)
{
string code = lbModules.SelectedItem.Text;
int week = 1;
UpdateTextBox(week, code);
}
`
The listbox is being populated elsewhere with a method looping and adding values with listbox.items.add
I have tried
listbox.SelectedItem.Text, listbox.SelectedValue.Text, listbox.SelectedItem.Value, listbox.SelectedValue.Value,
Nothing I try returns the text of the selected value, always throws an exception or returns null.
Ok, first up, it does not make much sense to use the selected index change event UNLESS you have a autopostback=true.
So, if the user is to enter some info into text box etc., then the user say hits your submit button, then I not really sure of any value of using the selected index change event. But, with autopost-back it does.
hence, this markup:
<h2>Select Hotels</h2>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true"
DataValueField="ID"
DataTextField="HotelName"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
Width="190px" Height="160px" >
</asp:ListBox>
<h3>Selected value</h3>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
And code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
string strSQL =
"SELECT ID,HotelName FROM tblHotelsA ORDER BY HotelName";
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
DataTable rstData = new DataTable();
rstData.Load(cmdSQL.ExecuteReader());
ListBox1.DataSource = rstData;
ListBox1.DataBind();
}
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex >= 0)
{
TextBox1.Text = ListBox1.SelectedItem.Value;
TextBox2.Text = ListBox1.SelectedItem.Text;
}
}
Note VERY but BEYOND careful that we ONLY load the listbox ONE time. Since for any event trigger on a page, the on-load event fires first, and THEN you code stub for the given button or event. Thus, if you load up the lb, or grid or in fact "any" data, but fail to include the all important if !IsPostBack code stub?
Then you cannot actually build a working web page!!! (so, my last 200+ web pages I have built ALL have and ALWAYS have that real first page load, since as noted, the on-load event triggers always on post-backs. So, if you load up the lb or anything again, it will blow out and overwrite your selections you have made).
So, above results in this:
However, if user is to enter data, select things, and THEN hit a submit button, then of course you probably would remove the autopostback = true. And place the above code behind the button click, and NOT use the selected index change event.
Even if you add items to the lb with code, the above rules still apply.
So, say this listbox:
<h2>Select Hotels</h2>
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
Width="190px" Height="160px" >
</asp:ListBox>
<h3>Selected value</h3>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
We still need the autopostback, and thus this code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadData();
}
void LoadData()
{
for (int i = 1; i <= 6; i++)
{
string MyText = "Item # " + i;
ListBox1.Items.Add(new ListItem(MyText, i.ToString()));
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex >= 0)
{
TextBox1.Text = ListBox1.SelectedItem.Value;
TextBox2.Text = ListBox1.SelectedItem.Text;
}
}
And now we get/see this:
So, either you are missing autopostback, or you are re-running your code to fill the lb each time on post-back, and that will as noted blow out any selecting the user makes.

Multiview controls

I wrote the following code for multiview where I am using gridview and datalist:
<ContentPlaceHolderID="ContentPlaceHolder1">
<div class="alert alert-success" >
<div class="divbtn" style="text-align:right">
<asp:LinkButton ID="gridbtn" runat="server" CssClass="glyphicon glyphicon-th" OnClick="gridbtn_Click"></asp:LinkButton>
<asp:LinkButton ID="listbtn" runat="server" CssClass="glyphicon glyphicon-th-list" OnClick="listbtn_Click"></asp:LinkButton>
</div>
</div>
<asp:MultiView runat="server" ID="multiview" ActiveViewIndex="0">
<asp:View runat="server" ID="gridview">
<uc1:GridControl runat="server" ID="GridControl"/>
</asp:View>
<asp:View runat="server" ID="listview">
<uc1:Listing runat="server" ID="Listing" />
</asp:View>
</asp:MultiView>
</asp:Content>
I am using two link buttons to call their respective views by firing two separate events as follows.
protected void listbtn_Click(object sender, EventArgs e)
{
multiview.ActiveViewIndex = 1;
}
protected void gridbtn_Click(object sender, EventArgs e)
{
multiview.ActiveViewIndex = 0;
}
Suppose, my datalist (Index=1) is active on my page and if there is a post back it should still be showing the datalist but on postback it automatically switches back to grid view (Index=0). I really need help with this!
You can save the index to a session variable and then read it back on post back like this:
To save:
Session["index"] = index.ToString();
Read it on page load like this:
Index = Session["index"];
You will need the session variable to maintain state per user session. If you want to maintain state for the application then you have to use the application variable.
Hi add the following code in your page_load event.
if(!Page.IsPostBack)
{
multiview.ActiveViewIndex=0;
}
i think you are setting the multiview's active index to zero on every post back like follows
protected void Page_Load(object sender, EventArgs e)
{
multiview.ActiveViewIndex=0;
}
this will cause the multiview to set active index as 0 on every post back.To avoid this you have to set it as follows
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
multiview.ActiveViewIndex=0;
}
}

ImageButton open link in new page within Repeater

I have the below Image Button which resides in a Repeater:
<asp:ImageButton PostBackUrl='<%# DataBinder.Eval(Container.DataItem, "VesselId", "getattachment.do?VesselId={0}") %>' CausesValidation="false" ID="insurancestatus" runat="server"/>
So every time the user clicked on the button they were shown their attachment.
The requirement has since changed, and the attachment must open on a new page so I added the following to the Repeaters ItemDataBound event:
ImageButton imagebuttonInsurance = (ImageButton)e.Item.FindControl("insuranceStatus");
imagebuttonInsurance.OnClientClick = String.Format("aspnetForm.target = '_blank'; return true()");
Now when I click on the image it does open another page but it just reloads the previous page on the new page. I tried removing the PostBackUrl and wiring up the following click event:
protected void insurancestatus_Click(object sender, ImageClickEventArgs e)
{
Vessel vessel = (Vessel)e.Item.DataItem;
Response.Redirect(String.Format("~/Secure/getattachment.do?VesselId={0}", vessel.VesselId));
}
But I couldn't get a handle on the item so cannot use the VesselId for the link, where am I going wrong here?
Use the second method, but use the command argument property like:
<asp:imagebutton runat=server...... commandargument='<%# Eval("vesselid") %>' />
then:
protected void insurancestatus_Click(object sender, ImageClickEventArgs e)
{
string vesselId = ((ImageButton)sender).CommandArgument;
Response.Redirect(String.Format("~/Secure/getattachment.do?VesselId={0}", vesselId));
}

A pragmatical point of view to ASP.NET's page cycle

I have a form like the following:
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plcHolder" runat="server">
</asp:PlaceHolder>
<asp:Button ID="btnSubmit" Text="submit" runat="server"
onclick="btnSubmit_Click" />
</div>
</form>
And here is my code:
protected string FetchDataFromDatabase()
{
return "some long string";
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.plcHolder.Controls.Add(new Label() { Text = FetchDataFromDatabase() } );
}
}
Page_Load() gets a long string from the database.
protected void btnSubmit_Click(object sender, EventArgs e)
{
this.plcHolder.Controls.Add(new Label() { Text = "new text" });
}
My Button adds new text to my page. However, when I click the button, I only see the string "new text" but I was looking for both texts ("some long string new text") instead.
I don't want to call my database at every button click since the text already loaded to the page. How do I achieve this?
I know that this example seems a little weird, it's because I tried to give the minimal working example.
In the load, when you get the value from the database, store it in Session:
Session["textFromDatabase"] = GetTextFromDatabase();
and then leverage that value in both places. So if you were in the click you would say:
... Text = Session["textFromDatabase"] + " new text";
and now you can get the value from the database when it's not a post back, just once like you stated, but leverage it over and over.
And I'm pretty sure, based on what you said, this is the inverse of the condition you want, throw a ! in front of it:
if (Page.IsPostBack)

How to get Text property of TextBox after ItemCommand event

I have a TextBox control inside a panel and this panel is inside DataList ItemTemplate.
After firing the ItemCommand event, everything works fine except that the TextBox.Text property is always an empty string "" although there is some text in it.
I tried several ways but without success. I would really appreciate if someone can assist me with this. Simplified code is shown below.
Thank you!
ASPX page:
<asp:DataList ID="dlDataList" runat="server" onitemcommand="dlDataList_ItemCommand">
<ItemTemplate>
<asp:Panel ID="pnlReply" runat="server" Visible="False">
<asp:TextBox ID="txtTextBox" runat="server"></asp:TextBox><br />
<asp:LinkButton ID="lnkbtnSend" CommandName="Send" runat="server">Send</asp:LinkButton>
</asp:Panel><br />
<asp:LinkButton ID="OpenPanel" CommandName="OpenPanel" runat="server">Open panel</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</asp:Content>
ASPX.CS Page code behind
protected void Page_Load(object sender, EventArgs e)
{
FillDataList();
}
private void FillDataList()
{
List<string> list = new List<string>();
list.Add("First");
list.Add("Second");
list.Add("Third");
dlDataList.DataSource = list;
dlDataList.DataBind();
}
protected void dlDataList_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "OpenPanel")
{
Panel pnlReply = (Panel)e.Item.FindControl("pnlReply");
pnlReply.Visible = true;
}
if (e.CommandName == "Send")
{
TextBox txtTextBox = (TextBox)e.Item.FindControl("txtTextBox");
//I tried this way also..
//TextBox txtTextBox = (TextBox)e.item.FindControl("pnlReady").FindControl("txtTextBox");
Label1.Text = txtTextBox.Text;
}
}
Please use IsPostBack in page load event. Without it your FillDataList(); is executing on every postback and resetting your DataList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDataList();
}
}

Categories

Resources