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
Related
I have an asp.net user control with 3 DropDownLists i.e (ddlState, ddlOffice and ddlOfficeType)
ddlState loads all states
ddlOffice loads offices in the selected state
while ddlOfficeType loads office types in the selected office.
In the user control file (.ascx.cs), I have the below on Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
//if (!Page.IsPostBack)
//{
PopulateStates();
Session[PageName + "State"] = ddlState.SelectedValue;
//}
}
When the state selection changes, I have that event handled as below
protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
string previousStateSelection = null;
if (Session["State"] != null)
{
previousStateSelection = Session["State"].ToString();
}
PopulateOffices(int.Parse(ddlState.SelectedValue));
Session[PageName + "State"] = ddlState.SelectedValue;
}
Now when I select a state in the 1st DropDownList, the related offices are populated correctly with the first office in the list selected.
The issue I'm facing is that when I now change the office selection in the 2nd DropDownList such that I load the 3rd DropDownList with office types related to the selected office, my new office selection is not retained on PostBack.
It's like my ddlOffice DropDownList is being refreshed & reset.
In Page_Load, I have no other code that might be reloading the DropDownList.
If I uncomment my check of IsPostBack to the below
if (!Page.IsPostBack)
{
PopulateStates();
Session[PageName + "State"] = ddlState.SelectedValue;
}
Then even the first ddlState does not load anything on PostBack, both ddlState & ddlOffice return empty.
Below is how I'm databinding the DropDownLists:
Load states (All)
private void PopulateStates()
{
if (ddlState.Items.Count > 0)
return;
States = GetStates()
ddlState.ClearSelection();
ddlState.Items.Clear();
ddlState.DataSource = States;
ddlState.DataTextField = "State_Name";
ddlState.DataValueField = "State_ID";
ddlState.DataBind();
}
Load offices based on selected state
private void PopulateOffices(int stateId)
{
var offices = new List<Office>();
offices = GetofficesBystateId(stateId).OrderBy(s => s.OfficeName).ToList();
ddlOffice.ClearSelection();
ddlOffice.Items.Clear();
ddlOffice.DataSource = offices;
ddlOffice.DataTextField = "OfficeName";
ddlOffice.DataValueField = "OfficeId";
ddlOffice.DataBind();
ddlOffice.SelectedIndex = ddlOffice.Items.IndexOf(ddlOffice.Items.FindByText(ddlOffice.Text));
}
Load office types based on selected office
private void PopulateOfficeTypes(int officeId)
{
var officeTypes = GetofficeTypesBySite(officeId);
ddlOfficeType.ClearSelection();
ddlOfficeType.Items.Clear();
ddlOfficeType.DataSource = officeTypes;
ddlOfficeType.DataTextField = "OfficeType";
ddlOfficeType.DataValueField = "OfficeTypeId";
ddlOfficeType.DataBind();
}
In the markup, all DropDownLists have
runat="server" AutoPostBack="True" EnableViewState="true"
2nd DDL's SelectedIndexChanged event handler.
protected void ddlOffice_SelectedIndexChanged(object sender, EventArgs e)
{
PopulateOfficeTypes(int.Parse(ddlOffice.SelectedValue));
Session[PageName + "Office"] = selectedValue;
}
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"
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
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);