ASP.NET dynamically created textbox doesn't change value - c#

I have the following issue:
I create a TextBox dynamically in my web page, its value is "initialVal" in the beginning.
Now I need to make a postback (not callback) to the server, and during this operation, I need to compute/change the value of my textbox to other value.
Here's an example:
protected void Page_Load(object sender, EventArgs e)
{
TextBox txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
txtBox.Text = "initialVal";
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
The problem: even if I change the value via code, the textbox will keep the text "initialVal". I feel this is something related to the view state, but I don't understand.
Coudl anyone please help me here?
Thanks.

Everytime you load the page it is running this:
txtBox.Text = "initialVal";
You should wrap this in a check for postback:
if (!Page.IsPostback)
{
txtBox.Text = "initialVal";
}
That said, onLoad is the wrong event to do the creation, for it to be valid in the early enough in the page lifecycle, use OnInit.
See this article on MSDN.
Here is the final code from #user2890888:
public partial class WebForm1 : System.Web.UI.Page
{
TextBox txtBox = null;
protected void Page_Init(object sender, EventArgs e)
{
txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtBox.Text = "initialVal";
}
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
}

Create your dynamic textbox creation in !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
if(!isPostBack){
TextBox txtBox = new TextBox();
txtBox.ID = "newButton";
form1.Controls.Add(txtBox);
txtBox.Text = "initialVal";
}
if (IsPostBack && Session["change"] == null)
{
txtBox.Text = "change";
Session["change"] = true;
}
}
Thanks and let me know if your issue still pending

Find the TextBox and use it
TextBox txtBox = (TextBox)FindControl("txtBox");
txtBox.Text = "change";

Even now you are having issue and your textBox is not getting the value you needed.
Store your new value for TEXTBOX in a hiddenfield.
I mean ,
if (IsPostBack && Session["change"] == null)
{
hiddenfield1.value = "change";
}
and later in your page script, you can assign back the value in this hiddenfield1 to textbox.
$(document).ready(
{
$('#txtBoxID').value=$('#hiddenfield1').value;
}
);

Related

Placeholder losing data after postback

I'm reading a list of id numbers from a database table into a placeholder textbox but however; if I do a button click the data is removed.
protected void btnSearch_Click(object sender, EventArgs e)
{
while (myReader.Read())
{
TextBox txt = new TextBox();
txt.Text = (string)myReader["idNumber"];
txt.ID = "txt" + i;
txt.ReadOnly = true;
ContentPlaceHolder1.Controls.Add(txt);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
i++;
}
}
This is a common problem when working with dynamically added controls in web forms (especially if you're coming from a winforms background). Pages in ASP.NET Web Forms are stateless, and reconstructed on each postback. Therefore, if you add a control to a page during a server event, you'll also have to add it to the page on subsequent Page loads if you want it to appear. You can accomplish this with something similar to the following:
protected List<Control> ControlCache
{
get => (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>());
set => Session["cachedControlsForPageX"] = value;
}
/* If you can't use C# 7's expression bodied property accessors, here's the equivalent in blocks:
protected List<Control> ControlCache
{
get { return (List<Control>)(Session["cachedControlsForPageX"] = (Session["cachedControlsForPageX"] as List<Control>) ?? new List<Control>()); }
set { Session["cachedControlsForPageX"] = value; }
}
*/
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
foreach (var control in ControlCache)
{
ContentPlaceHolder1.Controls.Add(control);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
}
}
else
ControlCache = null;
}
protected void btnSearch_Click(object sender, EventArgs e)
{
while (myReader.Read())
{
TextBox txt = new TextBox();
txt.Text = (string)myReader["idNumber"];
txt.ID = "txt" + i;
txt.ReadOnly = true;
ContentPlaceHolder1.Controls.Add(txt);
ContentPlaceHolder1.Controls.Add(new LiteralControl(" "));
ControlCache.Add(txt);
i++;
}
}

How to change button text on page load based on listview value on Visual Studio

I want to change my button text on page load after retrieving the list view values.
For example,
<asp:Label ID="favouriteLabel" runat="server" Text='<%# Eval("favourite") %>' />
If this label value is 1, the button will change to Favourited.
I have retrieved the list view values by binding the listview
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Label activity = (Label)e.Item.FindControl("favouriteLabel");
activityID = activity.Text;
}
}
then, I get the activityID and do a simple if-else check on the page load
protected void Page_Load(object sender, EventArgs e)
{
if (activityID == "1")
{
Button4.Text = "Favourited";
}
else
{
Button4.Text = "Favourite";
}
}
However it does not work. Anybody?
Do that inside a PostBack check in the load event, for instance:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (activityID == "1")
{
Button4.Text = "Favourited";
}
else
{
Button4.Text = "Favourite";
}
}
}
Read more about postback here
Page_Load happens before your ItemDataBound event so the activityId you are looking at in the Page_Load will never be 1.
Just put the code you have in the Page_Load into the ItemDataBoundEvent

How to display paragraph like content in DataGridView?

I am trying to develop an simple "Invoice" Windows application. I have bounded the textboxes (Item, Description, MRP, Quantity, etc.) to DataGridView but data entered by user in the "Description" textbox (multiline) has to be displayed as it is in GridView which is not happening in my code.
My code:
private void DS_Invoice_Load(object sender, EventArgs e)
{
this.allDataTableAdapter.Fill(this.database1DataSet4.AllData);
this.itemDataTableAdapter.Fill(this.database1DataSet3.ItemData);
this.custDataTableAdapter.Fill(this.database1DataSet2.CustData);
groupBox1.Enabled = false;
groupBox2.Hide();
groupBox3.Show();
groupBox3.Enabled = true;
max();
tb_inv_id.ReadOnly = true;
tb_order_id.Text = "-";
tb_net_amt.Text = "0";
tb_amt.Text = "0";
}
private void btnAddJob_Click(object sender, EventArgs e)
{
if (dataGridView1.Columns.Count == 0)
{
dataGridView1.Columns.Add("Item Name", "Name");
dataGridView1.Columns.Add("Description", "Description");
dataGridView1.Columns.Add("Qauntity", "Qauntity");
dataGridView1.Columns.Add("Rate", "Rate");
dataGridView1.Columns.Add("Amount", "Amount");
}
// Add the text box values to a new row in the DataGridView
dataGridView1.Rows.Add(new object[] { tbItemNm.Text, tbItemDscr.Text,
tb_quantity.Text,tb_rate.Text,tb_amt.Text});
MessageBox.Show("Item Added successfully..", "Add Job", MessageBoxButtons.OK);
tbItemNm.Clear();
tbItemDscr.Clear();
tb_quantity.Clear();
tb_rate.Clear();
tb_amt.Clear();
tbItemNm.Focus();
}
Try this example for wrapping text in grid view.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Attributes.Add("style", "word-break:break-all;word-wrap:break-word;width:100px");
}
}
}

Issue in row updating in gridview

I am using a grid view with auto generate column =true;
When I am updating the grid
protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
{
TextBox tPropertyId = (TextBox)row.FindControl("PropertyId");
}
is getting called.The proplem is thaT , tPropertyId is getting null value and when I am doing
tPropertyId.Text , I am getting null reference exception.
Please Help.
Please try this
protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
{
if (e.Row.RowType != DataControlRowType.Footer) return;
TextBox textBox = new TextBox();
e.Row.Cells[0].Controls.Add(textBox);
}

Create session in gridview cell

i have a gridview with tempaltefield buttons,
i want to create a session with value of a cell in selected button row ,
can anyone help me i tryed this but didnt work:
protected void ImageButton1_Click1(object sender, ImageClickEventArgs e)
{
Session["mysession"] = GridView1.SelectedRow.Cells[1].Text;
}
First of all, if it's just a imagebutton in a templatefield, actually you don't select de row. This line will problably throw an exception because SelectedRow is null.
But if you are using a command to select, that's correct. Maybe your event (ImageButton1_Click1) is not assigned to your image (OnClick).
You can try something like this:
protected void Page_Load(object sender, EventArgs e)
{
try
{
//Add and event RowDataBound
grvGrid.RowDataBound += new GridViewRowEventHandler(grvGrid_RowDataBound);
}
catch
{
//...throw
}
}
protected void grvGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.Header)
{
//...
}
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Add an ImageButton foreach row in GridView
ImageButton ibtImageAlt = new ImageButton();
ibtImageAlt.ImageUrl = "App_Images/y.gif";
//ImageButton's ID will be the index of the row
ibtImageAlt.ID = e.Row.RowIndex.ToString();
ibtImageAlt.ForeColor = System.Drawing.Color.White;
ibtImageAlt.Font.Overline = false;
ibtImageAlt.Click += ibtImageAlt_Click;
}
}
catch
{
//...throw
}
}
protected void ibtImageAlt_Click(object sender, EventArgs e)
{
try
{
//Catch the ImageButton ID and the row in GridView
//An example to catch the value of the row selected by the ImageButton
Int32 intIndexRow = Convert.ToInt32(((ImageButton)sender).ID);
String strTest = grvGrid.Rows[intIndexRow].Cells[0].Text;
}
catch
{
//...throw
}
}

Categories