Textbox losing value after another buttons postback - c#

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

Related

Need to set Property and open link at same time inside a TableCell

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");
}

Can't change DropDownList SelectedValue when Enabled = False in codebehind

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 :)

Retrieve the values from textbox which is dynamically created using C#

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);

Modal popup extender losing ID

Edit:
Added onload method:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
I'm using a modal pop up extender to warn my customers that the item amount of a specific item is over a certain amount.
I have two buttons within this extender that allows a user to confirm they want an email sending to them when new stock arrives or not.
The trigger for the 'yes' button works perfectly but when i send the row ID to the constructor of my class used to store the email details it is always set to 0, even though the variable is global.
Here is my code to explain the issue further:
Button within my modal to add items to the cart:
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow row = ((Button)sender).Parent.Parent as GridViewRow;
TextBox t = (TextBox)row.FindControl("txtQuan");
*********Gain the item row ID (this is what needs to be passed*******
object ID = GridView1.DataKeys[row.RowIndex].Value;
*********This ID should be passed but is setting to 0************
rowID = Convert.ToInt32(ID);
string qty = t.Text;
int stockToAdd = Convert.ToInt32(qty);
DBHandler add = new DBHandler(rowID);
int qtyCheck = add.getStockQty();
if (stockToAdd > qtyCheck)
{
Button2_ModalPopupExtender.Show();
}
else{
SqlConnection con;
con = add.openDB();
con.Open();
DBHandler idCheck = new DBHandler(rowID);
int rows = idCheck.checkCartRows();
if (rows > 0)
{
int qtyNow = idCheck.getCartQty();
int updateStock = qtyNow + stockToAdd;
idCheck.updateQty(rowID, updateStock);
updatePanel();
}
else
{
idCheck.insertCart(qty);
updatePanel();
}
add.close();
}
}
The following code shows my confirm onclick button method. Note the ID 'rowID' that was stored in the above method when the add to cart button was clicked. This rowID is is setting to 0 instead of holding the rowID value.
protected void btnOK_Click(object sender, EventArgs e)
{
***** rowID is setting to 0*******
DBoutOfStockEmail insertNewEmailDetail = new DBoutOfStockEmail(IDMaster, rowID);
DBMembershipHandler getEmail = new DBMembershipHandler(IDMaster);
string emailToSend = getEmail.emailOfMember();
insertNewEmailDetail.insertDetails(emailToSend);
}
To summaries this question: Why is the rowID variable setting to '0' when i click the yes button with the modal pop up extender?
Based on my initial Comment I am going to post this as an answer
This can be from several things.. are you checking or doing IsPostBack checks, are you holding the Value(s) in a Session Variable..? ViewState is it enabled or disabled..? can you show what your Page_Load Event Looks like

OnPageIndexChanged Clashing with OnItemCommand

I am facing a slight problem with both events clashing with one another.
I have a column displaying a link button, so that when user clicks on it, it would direct them to another page displaying the data in the specific row of the datagrid.
Below the datagrid, I have number pages, which just so happens to be a link button as well and when user clicks on page 2, it would display the page 2 data of the datagrid.
The problem now is that, when I want to click to page 2, it would redirect to the next page, which is the event of my ItemCommand.
Are there any ways of which I could make the datagrid differentiate, which is the correct link button to read,
So that both of them do not clash with one another??
protected void RPYGrid_ItemSelect(object sender, DataGridCommandEventArgs e)
{
DataSet dsGenRequestPayment = new DataSet();
dsGenRequestPayment = GenerateRequestPayment();
DataTable dtRequest = new DataTable();
dtRequest = dsGenRequestPayment.Tables[0];
if (((LinkButton)e.CommandSource).CommandName == "ItemSelect")
{
try
{
int iIndex = e.Item.DataSetIndex;
string sId = RPYGrid.DataKeys[iIndex].ToString();
foreach (DataRow drRequest in dtRequest.Rows)
{
string sRequestID = drRequest["RequestNo"].ToString();
if (sId == sRequestID)
{
sRequestNo = drRequest["RequestNo"].ToString();
sAmount = drRequest["RequestAmt"].ToString();
sAttachment = drRequest["FilePath"].ToString();
sReqCompanyID = drRequest["RequestCompanyID"].ToString();
sPayCompanyID = drRequest["PayerCompanyID"].ToString();
sReqCoName = drRequest["RequestCoName"].ToString();
sPayCoName = drRequest["PayerCoName"].ToString();
sRequestDate = drRequest["RequestDt"].ToString();
}
}
dtRequest.Clear();
dsGenRequestPayment.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
protected void RPYGrid_PageIndexChanged(object sender, DataGridPageChangedEventArgs e)
{
RPYGrid.CurrentPageIndex = e.NewPageIndex;
GenerateRequestData();
}
Does that still happen to you by having different command names in your linkbuttons?
I think I didnt understand very well your question
is this what you want to do ?
Select Case (CType(e.CommandSource, LinkButton)).CommandName
Case "paging"
'dopaging
case "redirect"
'doredirect
Case Else
End Select

Categories

Resources