I have created few textbox dynamically while coding in the flow I have provided unique id for each and I have hard coded some values to all the text boxes using C#.
Now on click of button am trying to retrieve the values from the textbox for which I have used the below code, but its throwing an exception as OBJECT REFERENCE NOT SET TO INSTANCE OF AN OBJECT.
Please look at the below code, I have tried both the things but still am not getting. Please help me out.
Thanks
protected void btnPltGrap_onclick(object sender, EventArgs e)
{
//spny is my stack panel and txtX0 is my of the text box id
//Below is the 1st Try
TextBox tb = new TextBox();
tb= (TextBox)Master.FindControl("spnY").FindControl("txtX0");
string strx = tb.Text;
//Below is the 2nd Try
string strx = (spnY.FindControl("txtX0") as TextBox).Text;
}
Thanks
Am trying to use view state as per you told that i shlould recreate the controls ones again but am getting exception as Invalid Arguments. please go have a look.
protected void btnSet_onClick(object sender, EventArgs e)
{
Table tblMainY = new Table();
TableRow tblRow = new TableRow();
tblMainY.Controls.Add(tblRow);
TableCell tblCel = new TableCell();
TextBox txtdyn = new TextBox();
txtdyn.Text = "1";
txtdyn.ID = "txtY01";
txtdyn.Width = 50;
tblCel.Controls.Add(txtdyn);
tblRow.Controls.Add(tblCel);
splY.Controls.Add(tblMainY);
ViewState["temptbl"] = tblMainY
}
protected void btnPltGrap_onclick(object sender, EventArgs e)
{
splY.Controls.Add(ViewState["Temptbl"]);
}
Please help me out
I've had the same problem in the past.
What I did was give the dynamically-added control an ID, and made sure it retained that ID also on postback.
Once the postbacked control has the same ID as as before, Microsoft did magic and refilled the controls with the pre-postback values.
Read out this code once
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
this.NumberOfControls = 0; //very first time when page is loaded, value will be 0
else
this.createControls(); //if it is postback it will recreate the controls according to number of control has been created
}
//this is the base of this, it will hold the number of controls has been created, called properties
protected int NumberOfControls
{
get { return (int)ViewState["NumControls"]; }
set { ViewState["NumControls"] = value; }
}
//it will create the controls
protected void createControls()
{
int count = this.NumberOfControls;
for (int i = 0; i < count; i++) //loop for the total number of control.
{
TextBox tx = new TextBox(); //creating new control
tx.ID = "ControlID_" + i.ToString(); //in your solution you are giving static id, don't do that, assign id number dynamically, it will help you further, if you want to manipulate the controls for some other use
//Add the Controls to the container of your choice
form1.Controls.Add(tx);
}
}
//add new control
protected void addSomeControl()
{
TextBox tx = new TextBox();
tx.ID = "ControlID_" + NumberOfControls.ToString();
form1.Controls.Add(tx);
this.NumberOfControls++; //increment the number of control
}
protected void AddBtn_Click(object sender, EventArgs e)
{
addSomeControl();
}
Default.aspx
take placeholder tag in aspx file
< asp:PlaceHolder ID="PlaceHolder1" runat="server">
Default.aspx.cs
// adding/creating dynamic text box
TextBox txt = new TextBox();
txt.ID = "New_txt";
txt.TextMode = TextBoxMode.MultiLine;
txt.Text = dt.Rows[0]["message"].ToString();
txt.Width = 802;
txt.Height = 450;
txt.ReadOnly = true;
PlaceHolder1.Controls.Add(txt);
Retrive value from text box
string str = txt.Text;
some sample code in bellow link as my blog
Its explain for how to put and get textboxe's with values and validations in dynamicaly using panel control .
Let's go this url . and you can get good solutions
get and Create dynamic Textbox and dropdownlist with Validation
simple line for get textbox values in
TextBox objTextBox = (TextBox)PlaceHolder.FindControl("CorrecttextBoxName");
string value=objTextBox .Text;
You must recreate your controls on init to get it's value.
Here are some links
Get text from dynamically created textbox in asp.net
Edit 1
TextBox tb=(TextBox)ViewState["Temptbl"];
splY.Controls.Add(tb);
Related
I have an asp:Table that is populated in the code behind with TableCells.
I started at this Q&A and was able to set up hyperlinks to the desired page. However, I need to set a C# Property as the link is being clicked.
The first column of the Table has names, my goal was to make the names clickable links that would open a new window or tab (different URL) and pass a Property like described here (In the section : Getting Public Property Values from the Source Page) for the next page to use.
I made the property but for the life of me can't figure out how to set the property as the link is being clicked. I've tried using Hyperlink, Linkbutton, and Button as well as having an HTML a href string placed in the cell.
I think LinkButton came the closest but it did not have a UseSubmitBehavior option to set to false so the link would not process.
I thought that this would be a simple process, set the property and then follow the link.
EDIT
Currently, have the code below, When I click the buttons nothing happens, it never enters the link_Click event, p.ID is what I am going to set the property to, I think I can get it from sender or e parameters somehow.
foreach (Person p in people)
{
DivDetail.Visible = true;
TableRow tRow = new TableRow();
Table2.Rows.Add(tRow);
TableCell tCell = new TableCell();
Button link = new Button();
link.Text = p.FullName;
link.ToolTip = p.ID;
link.UseSubmitBehavior = false;
link.Attributes.Add("OnClick", "link_Click");
tCell.Controls.Add(link);
tCell.Font.Bold = true;
tRow.Cells.Add(tCell);
//other cells of row populated
}
void link_Click(object sender, EventArgs e)
{
Response.Redirect("/Orig.aspx");
}
I think you are looking for a QueryString item. You can put a variable in the url that is being clicked and read that variable on the other page.
Lets say in page 1 you create the hyperlink with the url, and you want to send a variable called myVariable to the next page. You can add it to the link
HyperLink link = new HyperLink();
link.NavigateUrl = "/Page2.aspx?myVariable=" + myVariable;
link.Text = "My Link";
Now on Page 2 you can read that query string item again into a variable for use in code behind
if (Request.QueryString["myVariable"] != null)
{
string myVariable = Request.QueryString["myVariable"];
}
But you can also do a form post to another page, so all the form field items can be read on the other page. So you would add a LinkButton to page 1 and set it's PostBackUrl to page 2.
LinkButton linkbutton = new LinkButton();
linkbutton.PostBackUrl = "/Page2.aspx";
linkbutton.Text = "My LinkButton";
Now when the button is clicked you can get the posted items in code behind of page 2.
foreach (string key in Request.Form.Keys)
{
Response.Write(key + ": " + Request.Form[key] + "<br>");
}
A third option would be to do a normal PostBack on Page 1 and then set a Session and redirect to Page 2 and read the Session there.
LinkButton linkbutton = new LinkButton();
linkbutton.Click += Linkbutton_Click;
linkbutton.Text = "My LinkButton";
private void Linkbutton_Click(object sender, EventArgs e)
{
Session["myVariable"] = myVariable;
Response.Redirect("/Page2.aspx");
}
Assuming you need to set SomeProperty to someValue and then send the browser to someUrl, use a LinkButton and set its Click even handler up like this:
void MyLinkButton_Click(object sender, EventArgs e)
{
SomeProperty = someValue;
Response.Redirect(someUrl);
}
If the property value isn't available server-side, you can pass it in a hidden form variable:
void MyLinkButton_Click(object sender, EventArgs e)
{
SomeProperty = Request.Form["SomeField"];
Response.Redirect(someUrl);
}
Or, if it's a problem to set a form variable, you can set the value up using the OnCommand Method. Set it this way as you bind the table:
protected void Table_ItemDataBound(object sender, EventArgs e)
{
LinkButton lb = e.Item.FindControl("MyLinkID") as LinkButton;
lb.CommandArgument = someValue;
}
and read it this way:
void MyLinkButton_Click(object sender, EventArgs e)
{
SomeProperty = e.CommandArgument;
Response.Redirect(someUrl);
}
If you need to set a property on the destination page (which would make a little more sense) you'll have to temporarily store it in session...
void MyLinkButton_Click(object sender, EventArgs e)
{
Session["Temp"] = Request.Form["SomeField"];
Response.Redirect(someUrl);
}
...and then set it:
//This is the load event handler for the second page
public void Page_Load()
{
this.SomeProperty = Session["Temp"];
Session.Remove("Temp");
}
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"
I have an AddRow() method which generates a check box and a text box for each row in the table, I need to control the text visibility by checking the check box in the same row.
that seemed to be easy for the first while, since I can get the targeted text box ID but I dont know how to do it now.
here is my method:
private void AddRow(int nRowIndex, string strPaymentStatus,string PaymentRemark)
{
// checkBox -----------------------------------------------------------------
CheckBox objCheckBox = new CheckBox();
objCheckBox.ID = strBillID;
objCheckBox.Checked = false;
objCheckBox.CheckedChanged += new EventHandler(cbxPaymentStatus_CheckedChanged);
objCheckBox.AutoPostBack = true;
// textBox----------------------------------------------------------
TextBox objTbxRemark = new TextBox();
objTbxRemark.ID = BillID;
objTbxRemark.AutoPostBack = true;
}
CheckBox handler:
protected void cbxPaymentStatus_CheckedChanged(object sender, EventArgs e)
{
// here I can get the BillID (textBox ID) by a query, but I need to control its visibility from here
}
any help will be appreciated..
You can try to use
Page.FindControl("id")
If you can reconstruct the correct id. They probably follow some kind of pattern based on the parents controls
The you have to cast to TextBox
TextBox txt = Page.FindControl("id") as TextBox ;
txt.Visible =...
On my page I have 3 textboxes that hold values for Title, Description, Tips and keywords. When I click on a button it inserts the values into the database. When it posts back, the values are staying in the textboxes, and this is what I want.
The next part of the page has textboxes for Question, CorrectAnswer, Wrong1, Wrong2, Wrong3. When I click on the button to insert them into the database, that works, and after the button fires its event I have those 5 textboxes have a text value of null, so I can continue on adding the question and answers.
But when that button causes its postback, the values in the first textboxes disappear, and I don't want that because I have validation on the title textbox, because you can't add any questions and answers without the title in the textbox.
So how do I keep the values in the first textboxes when the second button causes a postback?
Here is the code for the two buttons, and the btnAddQandA is the button that causes a postback..
protected void btnAddQuizTitle_Click(object sender, EventArgs e)
{
daccess.AddQuizName(tbTitle.Text, taDescription.InnerText, taTips.InnerText, tbKeywords.Text);
Session["TheQuizID"] = daccess.TheID;
string myID = (string)(Session["TheQuizID"]);
int theID = Int32.Parse(myID);
if (tbKeywords.Text != null)
{
string TheKeywordHolder = "";
foreach (ListItem LI in cblGrades.Items)
{
if (LI.Selected == true)
{
TheKeywordHolder = TheKeywordHolder + LI.Value + ",";
}
}
daccess.AddQuizKeywords(theID, tbKeywords.Text);
}
}
protected void btnAddQA_Click(object sender, EventArgs e)
{
int theID = (int)Session["TheQuizID"];
daccess.AddQuizQA(tbQuestion.Text, tbCorrect.Text, tbWrong1.Text, tbWrong2.Text, tbWrong3.Text, theID);
tbQuestion.Text = null;
tbCorrect.Text = null;
tbWrong1.Text = null;
tbWrong2.Text = null;
tbWrong3.Text = null;
}
and here is my pageload event
DataAccess daccess = new DataAccess();
protected void Page_Load(object sender, EventArgs e)
{
daccess.CblGradesDS();
cblGrades.DataSource = daccess.DsCbl;
cblGrades.DataValueField = "GradeID";
cblGrades.DataTextField = "Grade";
cblGrades.RepeatColumns = 8;
cblGrades.RepeatDirection = RepeatDirection.Horizontal;
cblGrades.DataBind();
daccess.CblSubjectsDS();
cblSubjects.DataSource = daccess.DsCbl2;
cblSubjects.DataValueField = "SubjectID";
cblSubjects.DataTextField = "SubjectName";
cblSubjects.RepeatColumns = 4;
cblSubjects.RepeatDirection = RepeatDirection.Horizontal;
cblSubjects.DataBind();
if (!IsPostBack)
{
}
}
These issues are usually caused by control IDs (UniqueIDs to be specific) that do not match before and after the postback. This causes inability of finding values in viewstate. This happens when you modify the controls collection (typically in codebehind) or when you change controls' visibility. It may also happen when you modify IDs before Page_Load event when viewstate is not yet populated. It's good to know how ASP.NET lifecycle works. http://spazzarama.com/wp-content/uploads/2009/02/aspnet_page-control-life-cycle.jpg
Good afternoon,
I have a DropDownList that I am setting Enabled = false in the code behind OnPageLoad. Later when I press the save button on the page I try to extract the data and I get a weird value from the disabled DropDownList and correct values from the Enabled DropDownList's.
My question is, how can I disable the DropDownList OnPageLoad so the users can't change the data but still modify it's data in the code behind file and extract it when needed? I see that the enabled property sets the read-only flag and I tried enabling the drop down before modifying it's data but it didn't work. Any ideas?
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i <= Convert.ToInt32(txtNumPrizes.Text.Trim()); i++)
{
DropDownList dl = new DropDownList();
bool disableRow = true; //example
dl.ID = "DDPrize" + i.ToString();
dl.DataSourceID = "SqlDataSource1";
dl.DataTextField = "PrizeName";
dl.DataValueField = "PrizeID";
Panel1.Controls.Add(dl);
dl.DataBind();
if (disableRow == true)
{
dl.Enabled = false;
}
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
for (int i = 1; i <= Convert.ToInt32(txtNumPrizes.Text.Trim()); i++)
{
DropDownList dd = (DropDownList)Panel1.FindControl("DDPrize" + i.ToString());
//disable the row if prize was already assigned to a player
int place = 1; //example
int selectedValue = DropDownSelect(i, place, GetTournamentID());
dd.SelectedValue = selectedValue.ToString(); //sets properly here
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
for (int i = 1; i <= numPrizes; i++)
{
DropDownList dd = (DropDownList)Panel1.FindControl("DDPrize" + i.ToString());
string key = dd.SelectedValue;//here is where we can't get the selected value :(
}
}
If you disable it in code, then when it renders they can't change the selection. The SelectedItem will possibly be null/Nothing depending on whether you set any of the items to Selected=true.
It doesn't make much sense [to me, anyway] using a dropdown that can't be used. Unless of course it's waiting on a postback for enabling it based on certain criteria.
You could disable it with jQuery on page load, and .NET wouldn't care. No matter what, it will let you access the value, or lack thereof, which is what you might be missing. Again, you'll still run into the issue that there's no SelectedItem if you haven't set one in the web form or in code.
Posting the code will help us help you further :)