ASP.net : textChange Partial Update for programmatically inserted textboxes - asp.net

I trying get some programmatically inserted textboxes (inserted into a gridview) to do a textChange partial update. It is sort of working but it does not automatically calls textEntered() method after I typed some text in these textboxes. I got a clue that I might need to use AJAX and things like updatepanels but I just don't fully understand how they will work in the context of what I am trying to do.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (!e.Row.Cells[4].Text.Equals(" ") && firstTime == false)
{
TextBox tb = new TextBox();
tb.Text = e.Row.Cells[4].Text;
tb.TextChanged += new EventHandler(textEntered);
textBoxArray.Add(tb);
int length = textBoxArray.Count - 1;
tb = (TextBox)textBoxArray[textBoxArray.Count - 1];
e.Row.Cells[4].Text = null;
e.Row.Cells[4].Controls.Add(tb);
Cache["textBoxArray"] = textBoxArray;
} firstTime = false;
}
protected void textEntered(object sender, EventArgs e)
{
lbl_test.Text += "test";//This line is for testing purposes
}

auto postback of textbox is true or false? make it true.

Related

Retrieving a Dynamically Generated TextBox Content in a GridView in ASP.NET

I have the following RowDataBound method for GridView2
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
List<TextBox> list = new List<TextBox>();
if (ViewState["Table"] != null)
Assessments = (DataTable)ViewState["Table"];
int count = 1;
foreach (DataRow row in Assessments.Rows)
{
TextBox txt = new TextBox();
txt.ID = "AsTxt";
txt.Text = string.Empty;
txt.TextChanged += OnTextChanged;
e.Row.Cells[count].Controls.Add(txt);
count += 2;
listd.Add((e.Row.DataItem as DataRowView).Row[0].ToString() + "Txt");
}
}
}
And the following event (Button Click) to retrieve whatever written in the text box in the GridView
protected void CalculateBtn_Click(object sender, EventArgs e)
{
GridViewRow rr = GridView2.Rows[0];
TextBox rrrr = (rr.FindControl("AsTxt") as TextBox);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rrrr.Text + "')", true);
}
I always get NullReferenceException. That mean the TextBox object (rrrr) is null always. I am sure that the text object sits in GridView2.Rows[0].
Why is this happening?
This is known issue with the Dynamical created controls in asp. So if you want to use the created control on your postback then I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.
Look at this blog this might help you
http://techbrij.com/retrieve-value-of-dynamic-controls-in-asp-net

why chk.Checked ChangedEventHandler is not triggered and i get the exception Object reference not set to an instance of an object

I try to make a simple application in which I have a dropdown list with tems - numbers from 1 to 4.
Depending on the number the user choose - I create dynamically this number of checkboxes with binded checkedchanged event. So when the user checks some of the checkboxes so checkedchanged event is raised and I store the text of the checked checkbox in session and then when I click a button I want to see the text only from the checked checkboxes.
But it seems that the checkedchanged event handler is never triggered.
Thank you in advance
public partial class proba : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
dd1.Items.Add("1");
dd1.Items.Add("2");
dd1.Items.Add("3");
dd1.Items.Add("4");
}
protected void dd1_SelectedIndexChanged1(object sender, EventArgs e)
{
int numTourists = Convert.ToInt32(dd1.SelectedItem.Text);
for (int i = 0; i < numTourists; i++)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + i;
chk.Text = "box" + i;
chk.CheckedChanged += new EventHandler(checkChanged);
Page.FindControl("form1").Controls.Add(chk);
}
}
protected void checkChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
lblpr.Text += chk.Text;
Session["chk"] = chk.Text;
}
protected void btnpr_Click(object sender, EventArgs e)
{
lblpr.Text = "length" + ((String [] )Session["chk"]).Length;
for (int k = 0; k < ((String[] )Session["chk"]).Length; k++)
{
lblpr.Text += ((String [])Session["chk"])[k];
}
}
}
You need to set AutoPostBack property of checkbox as true in order to post back when check changed
chk.AutoPostBack = true;
And read this also
adding an event handler to a dynamically created checkbox (aspx, c#)
change page load, you don't need to add items again and again in each page post back
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Load dd1
}
}
But you need to add dynamic controls on each page post back, better do it on OnInit as above answer in the link suggested
since you are creating checkbox dynamically, it get lost when there is the post back.
So you need to add those again before pageload event so that during page load event they are visible to .net and hence .net can fire their corresponding event.
B4 you dive into dynamic control it is good idea to get the basic which can be found at https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx

asp.net gridview outside button to save

I have gridview built dynamically at run-time bind to datatable, and button to save gridview data placed outside gridview
1- Create GridView
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
CreateGrid();
}
}
void CreateGrid()
{
int nTransID = Convert.ToInt32(Session["trans_id"]);
//
string strSQL = #"EXEC [dbo].[sp_GetTransaction] " + nTransID;
DataTable dtData = clsGlobal.GetDataTable(strSQL);
//
if (ViewState["dtTransDetail"] == null) ViewState.Add("dtTransDetail", dtData);
else ViewState["dtTransDetail"] = dtData;
//
foreach (DataColumn dc in dtData.Columns)
{
if (dc.ColumnName.Contains("!;"))
{
TemplateField tField = new TemplateField();
tField.ItemTemplate = new AddTemplateToGridView(ListItemType.Item, dc.ColumnName);
//\\ --- template contain textbox
tField.HeaderText = dc.ColumnName;
GridView1.Columns.Add(tField);
}
}
}
This is my template class:
public class AddTemplateToGridView : ITemplate
{
ListItemType _type;
string _colName;
public AddTemplateToGridView(ListItemType type, string colname)
{
_type = type;
_colName = colname;
}
void ITemplate.InstantiateIn(System.Web.UI.Control container)
{
switch (_type)
{
case ListItemType.Item:
TextBox text = new TextBox();
text.ID = "txtAmount";
text.DataBinding += new EventHandler(txt_DataBinding);
container.Controls.Add(text);
break;
}
}
void txt_DataBinding(object sender, EventArgs e)
{
TextBox textBox = (TextBox)sender;
GridViewRow container = (GridViewRow)textBox.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _colName);
if (dataValue != DBNull.Value)
{
textBox.Text = dataValue.ToString();
}
}
}
So i have a gridview with textboxe's all open to edit at once
The problem is, when i click on Save button "which is outside gridview" all textboxe's gone
protected void btnSave_Command(object sender, CommandEventArgs e)
{
for (int nRow = 0; nRow < GridView1.Rows.Count; nRow++)
{
for (int nCol = 0; nCol < GridView1.Columns.Count; nCol++)
{
if (GridView1.Rows[nRow].Cells[nCol].Controls.Count == 0) continue;
//\\ --- Controls.Count always = 0
//\\ --- However each cell contain textbox
//\\ --- textbox disappear after save button clicked
TextBox txt = (TextBox)GridView1.Rows[nRow].Cells[nCol].Controls[0];
}
}
}
It looks like you are not creating the GridView after a postback, and the Save button is causing a postback. You need to dynamically create the GridView on each page load. Also, I have found this documentation on the ASP.NET page lifecycle helpful on numerous occasions.
In the documentation, you will see the slightly unintuitive reason why your code isn't working as you would like - btnSave_Command is not run until after a postback and Page_Load.

asp.net get the text from a dynamically inserted textbox return null all the time

I am writing a web app in asp.net, in one of my aspx pages I have a static table.
To this table I insert a dynamically textbox control from the code behind (from Page_Load, I create this control dynamically because I do not know if I need to create it or not it depend on a user answer), the problem is when i try to get the textbox text after the user click on a button, I tried every thing i know from Request.Form.Get("id of the control") to Page.FindControl("id of the control"), but nothing works I get null all the time, just to be clear the button that activate the function that get the text from the textbox is insert dynamically to.
Both button and textbox are "sitting" in a table and must remain so, I'd appreciate any help
my code is:
aspx page
<asp:Table ID="TabelMessages" runat="server"></asp:Table>
code behind aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.ID = "textBox";
tb.Text = "hello world";
TableCell tc = new TableCell();
tc.Controls.Add(tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
}
public void Button_Click(object o, EventArgs e)
{
string a = Request.Form.Get("textBox");//does not work
Control aa = Page.FindControl("textBox");//does not work
}
in your
public void Button_Click(object o, EventArgs e)
{
//try searching in the TableMessage.Controls()
}
Alternatively, and depending on what you ultimately want to do, and still use Page_Load:
In your Page Class:
protected TextBox _tb; //this is what makes it work...
protected void Page_Load(object sender, EventArgs e)
{
_tb = new TextBox();
_tb.ID = "textBox";
TableCell tc = new TableCell();
tc.Controls.Add(_tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
if (!Page.IsPostBack)
{
_tb.Text = "hello world";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = _tb.Text; //this will display the text in the TextBox
}
You need to run your code inside the Page_PreInit method. This is where you need to add / re-add any dynamically created controls in order for them to function properly.
See more information about these types of issues in the MSDN article on the ASP.NET Page Life Cycle.
Try changing your Page_Load code to the following:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
TextBox tb = new TextBox();
tb.ID = "textBox";
tb.Text = "hello world";
TableCell tc = new TableCell();
tc.Controls.Add(tb);
TableRow tr = new TableRow();
tr.Cells.Add(tc);
TabelMessages.Rows.Add(tr);
}

Call a button_click on page_load asp.net

I have a search textbox and a search button, when clicked displays a grid with the following names and gender.However I have redirected the page to another page on edit.Now When I comeback from that page to the page containing the gridview I want to display the same search again. I have successfully put retrieved the information but storing it into session, but I'm not able to call my btn_click event # page_Load.
Here's a snippet:
EDIT: I have made some changes in my code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
if (Session["FirstName"] != null)
txtSearch.Text = Session["FirstName"].ToString();
if (Session["Gender"] != null)
ddlGen.SelectedValue = Session["Gender"].ToString();
btnSearch_Click(sender, e);
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
and here's the click event:
protected void btnSearch_Click(object sender, EventArgs e)
{
string query = "Select EmployeeId,FirstName,Password,Address,sex,Deptno,act_book,actTV,DOJ,isActiveYN from employees where 1=1";
if (txtSearch.Text != "")
{
query += " and FirstName like '%" + txtSearch.Text + "%'";
Session["FirstName"] = txtSearch.Text;
}
if (ddlGen.SelectedValue != "")
{
query += " and sex='" + ddlGen.SelectedValue.ToUpper() + "'";
Session["Gender"] = ddlGen.SelectedValue;
}
DataSet ds = new DataSet("Employees");
SqlConnection con = new SqlConnection("Password=admin;User ID=admin;Initial Catalog=asptest;Data Source=dbsvr");
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.Fill(ds);
gvSession.DataSource = ds;
gvSession.DataBind();
}
Now I'm able to save search, so that problem is resolved ,but another has poped up that when I click the button search after changin text it takes me back to the older search..The reason is probably because sessions are not cleared,but I did that as well by handling textchanged and selectedindexchanged eventd.
Rather than trying to call your button click handler from the Page_Load, change your button click handler to simply call another method like:
protected void btnSearch_Click(object sender, EventArgs e)
{
RunSearch();
}
Then move all your btnSearch_Click() code into RunSearch()
Then in your Page_Load you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Gender"] != null && Session["FirstName"] != null)
{
txtSearch.Text = Session["FirstName"].ToString();
ddlGen.SelectedValue = Session["Gender"].ToString();
RunSearch();
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
On a side note, I would recommend taking a look into SQLCommand Parameters. Your code is prone to SQL Injection Attacks:
http://en.wikipedia.org/wiki/SQL_injection
You should reset the session redirected variable so it doesn't fall in the same case.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
Session["Redirected"] = null;
....
You can do using an QueryString paremeter when page return back to main page then here you can check QueryString paremeter is exist. here you can implement code for bind grid
if (Request.QueryString["Back"]!= null)
{
// Your bind grid function
}
You can create a function, which will called both from the button_click and page_load.

Resources