DropDownList-Items are null on postback - asp.net

I have DropDownList that I have to populate in an event associated with a click event of another control.. the data is populated and present but when I select a value and postback the values are null. Which means the view state is not working.. Solutions say that populate the DropDown in Init() but I can't because the requirement does not allow this. I have to populate it on click event .. Viewstates are enabled.. The following code populates the DropDown..
if (e.CommandName == "Add Friend")
{
HtmlGenericControl divMySub = (HtmlGenericControl)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("divMySubjects");
divMySub.Style["display"] = "block";
DropDownList mySub = (DropDownList)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("DropDownListMySubjectz");
UpdatePanel mySubPanel = (UpdatePanel)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("UpdatePanelRequestAction");
DataView SubjectTableView = ProfileDataAccess.GetUserUnusedSubjectsForRequest(UserId ,RequesterId).DefaultView;
if (SubjectTableView.Count > 0)
{
mySub.DataSource = SubjectTableView;
mySub.DataTextField = "Name";
mySub.DataValueField = "Id";
mySub.DataBind();
}
else
{
divMySub.InnerText = "Requests Complete";
LinkButton buttonlink= (LinkButton)sender;
buttonlink.Enabled = false;
}
mySubPanel.Update();
}
and the following is the code for the postback that retrieves the value from the Dropdown list.. The DropDown is inside a Gridview Row.
protected void LinkButtonAddFriend_Command(object sender, CommandEventArgs e)
{
Guid RequestedId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
Guid UserId = new Guid(HiddenFieldUserId.Value.ToString());
int UserSubjectId = Convert.ToInt32 (GridViewUserSubjects.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
DropDownList DDL = (DropDownList)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("DropDownListMySubjectz");
LinkButton RequestAction = (LinkButton)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("LinkButtonFriendAction");
int RequesterSubjectId = Convert.ToInt32(DDL.SelectedItem.Value);
if (FriendsDataAccess.InsertRequest(UserId, RequestedId, UserSubjectId, RequesterSubjectId))
{
RequestAction.Text = "Remove Request";
RequestAction.Enabled = true;
}
}
DDL is the Dropdown with trouble.

When are you databinding the GridView which is the container of the DropDownList? Do you have wrapped it in a if(!IsPostBack)-check? When you databind the GridView the child controls are always "resetted".
If you use a declarative databound control like ObjectDataSource you should avoid this.databind() if it's not necessary.

Related

Capturing the value of dynamically created TextBox and DropDownList in ASP.NET

I am stuck in an issue, tried googling but could not find any solution.
I have created controls dynamically in Page_Load and I have a static button.
When the button is clicked, I need to capture user entry in those controls.
Now when I am trying to access the control using its unique id, error is being returned as the control is not available at runtime. :(
For loop - starts
if (dr["Type"].ToString().Trim() == "DropDown")
{
DropDownList ddl = new DropDownList();
ddl.Id = "ddl" + Convert.ToString(Counter);
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataSource = ds1;
ddl.DataBind();
ddl.EnableViewState = true;
cell.Controls.Add(ddl);
}
else if (dr["QuestionType"].ToString().Trim() == "TextBox")
{
TextBox txt = new TextBox();
txt.ID = "txt" + Convert.ToString(Counter);
txt.EnableViewState = true;
cell.Controls.Add(txt);
}
row.Cells.Add(cell);
table.Rows.Add(row);
Even if i do a FindControl in Btn_click function, it says that the panel has 0 controls.
var textbox = (TextBox)pnlMidTermFeedback.FindControl("txt5");
textbox is always NULL, although I have a control txt5. I can see it when I do a F12.
Please help.
Dynamically created controls must be recreated on every postback:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Set values and properties of controls specified in markup
...
}
// Create new controls and add them to the panel
...
}
They will then be available in the button event handler, and contain the data entered by the user.

I have issue with viewstate of dropdown list [duplicate]

I have DropDownList that I have to populate in an event associated with a click event of another control.. the data is populated and present but when I select a value and postback the values are null. Which means the view state is not working.. Solutions say that populate the DropDown in Init() but I can't because the requirement does not allow this. I have to populate it on click event .. Viewstates are enabled.. The following code populates the DropDown..
if (e.CommandName == "Add Friend")
{
HtmlGenericControl divMySub = (HtmlGenericControl)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("divMySubjects");
divMySub.Style["display"] = "block";
DropDownList mySub = (DropDownList)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("DropDownListMySubjectz");
UpdatePanel mySubPanel = (UpdatePanel)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("UpdatePanelRequestAction");
DataView SubjectTableView = ProfileDataAccess.GetUserUnusedSubjectsForRequest(UserId ,RequesterId).DefaultView;
if (SubjectTableView.Count > 0)
{
mySub.DataSource = SubjectTableView;
mySub.DataTextField = "Name";
mySub.DataValueField = "Id";
mySub.DataBind();
}
else
{
divMySub.InnerText = "Requests Complete";
LinkButton buttonlink= (LinkButton)sender;
buttonlink.Enabled = false;
}
mySubPanel.Update();
}
and the following is the code for the postback that retrieves the value from the Dropdown list.. The DropDown is inside a Gridview Row.
protected void LinkButtonAddFriend_Command(object sender, CommandEventArgs e)
{
Guid RequestedId = new Guid(Membership.GetUser().ProviderUserKey.ToString());
Guid UserId = new Guid(HiddenFieldUserId.Value.ToString());
int UserSubjectId = Convert.ToInt32 (GridViewUserSubjects.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
DropDownList DDL = (DropDownList)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("DropDownListMySubjectz");
LinkButton RequestAction = (LinkButton)GridViewUserSubjects.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("LinkButtonFriendAction");
int RequesterSubjectId = Convert.ToInt32(DDL.SelectedItem.Value);
if (FriendsDataAccess.InsertRequest(UserId, RequestedId, UserSubjectId, RequesterSubjectId))
{
RequestAction.Text = "Remove Request";
RequestAction.Enabled = true;
}
}
DDL is the Dropdown with trouble.
When are you databinding the GridView which is the container of the DropDownList? Do you have wrapped it in a if(!IsPostBack)-check? When you databind the GridView the child controls are always "resetted".
If you use a declarative databound control like ObjectDataSource you should avoid this.databind() if it's not necessary.

how to define radio button CheckedChanged property after finding radio button in another control

i like to know how i have to use radio button CheckedChanged property when the radio button there is in gridview and this gridview itself is inside of 1 user control and user control is inside of detail view control.
before i have learned how i have to find radio button control in another control. but after finding i do not know how to make CheckedChanged property for that?
protected void btnShowAddTransmittaltoCon_Click(object sender, EventArgs e)
{
Transmittallistfortest transmittalList = (Transmittallistfortest)DetailsView1.FindControl("Transmittallistfortest1");
GridView g3 = transmittalList.FindControl("GridViewTtransmittals") as GridView;
foreach (GridViewRow di in g3.Rows)
{
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
//Giving Error:Object reference not set to an instance of an object.
if (rad != null && rad.Checked)
{
var w = di.RowIndex;
Label1.Text = di.Cells[1].Text;
}
Replace this
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
with this:
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
You won't get an exception but it may return NULL - in which case it'll be caught in the ifstatement: rad != null.
The whole point of using the as keyword is this:
as => won't throw an exception - it just reports null.
By the way: You should retrieve the RadioButton this way:
if(di.RowType == DataControlRowType.DataRow)
{
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
}
To define the CheckedChange event, do this:
//rad.Checked = true;
rad.CheckedChanged += new EventHandler(MyCheckedChangeEventHandler);
Then define the handler:
protected void MyCheckedChangeEventHandler)(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
if (rb.Checked)
{
// Your logic here...
}
}

textbox textchanged event always firing

I have a form with a few text-boxes and a Grid-view. There is this one text-box called "Inward Number", whose text-changed event fires all the time. When i want to fire another control's event, it simply fires the text-changed event of the Inward Number text-box. This happens with all of the other controls. Can someone please help?
protected void txtInward_No_TextChanged(object sender, EventArgs e)
{
a = 'A';
NewRow();
}
I have used the correct names, but still this error occurs.
<asp:TextBox ID="txtInward_No" runat="server" Width="220px" CssClass="txtbox"
EnableViewState="False"
AutoPostBack="True" ontextchanged="txtInward_No_TextChanged">
</asp:TextBox>
new row just makes a new row in my grid.
private void NewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtnew = new DataTable();
dtnew = (DataTable)ViewState["CurrentTable"];
DataRow drr = null;
if (dtnew.Rows.Count > 0)
{
for (int i = 1; i <= dtnew.Rows.Count; i++)
{
TextBox box1 = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("TextBox1");
TextBox box2 = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("TextBox2");
TextBox box3 = (TextBox)GridView1.Rows[rowIndex].Cells[4].FindControl("TextBox3");
TextBox box4 = (TextBox)GridView1.Rows[rowIndex].Cells[5].FindControl("TextBox4");
TextBox box5 = (TextBox)GridView1.Rows[rowIndex].Cells[6].FindControl("TextBox5");
drr = dtnew.NewRow();
if (txtInward_No.Text =="1")
{
drr["InwardNumber"] = txtInward_No.Text + b.ToString();
}
else
{
drr["InwardNumber"] = txtInward_No.Text + a.ToString();
}
drr["Bags"] = box1.Text;
drr["GrossWt"] = box2.Text;
drr["TareWt"] = box3.Text;
drr["NetWt"] = box4.Text;
drr["DCBillWt"] = box5.Text;
rowIndex++;
}
dtnew.Rows.Add(drr);
ViewState["CurrentTable"] = dtnew;
GridView1.DataSource = dtnew;
GridView1.DataBind();
}
}
PrevData();
b++;
a++;
}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.ontextchanged.aspx
A TextBox control must persist some values between posts to the server for this event to work correctly. Be sure that view state is enabled for this control.
Try enabling ViewState for TextBox.
I think what's probably happening is that ASP.NET relies on ViewState to decide whether the TextBox's value has changed. But you've disabled ViewState on this control. I'm not sure why it can't use ControlState instead, but you could try enabling ViewState for this TextBox and see if this has an effect.
The MSDN page on the OnTextChanged event mentions this.

template field (button) of the grid executing on page refresh

I have a button as template field in my hierarchical grid and on that button I am updating some data but when user hit the browser refresh button it executes by itself ..whats the solution..
here is my code behind
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (!Page.IsPostBack)
{
if (e.CommandName == "UpdateBillData")
{
GridViewRow row = ((Control)e.CommandSource).NamingContainer as GridViewRow;
int index = row.RowIndex;
int billgenID = Convert.ToInt32(GridView1.DataKeys[index].Value);
DropDownList ddmonths = (DropDownList)row.FindControl("DDBillingMonths");
TextBox cunit = (TextBox)row.FindControl("txtCurrBillUnits");
TextBox amountbDue = (TextBox)row.FindControl("txtAmountBDueDate");
TextBox advItax = (TextBox)row.FindControl("txtAdvIncomeTax");
TextBox whtax = (TextBox)row.FindControl("txtWholdingTax");
TextBox gst = (TextBox)row.FindControl("txtGst");
TextBox amountafterdd = (TextBox)row.FindControl("txtAmtAfterDD");
TextBox duedate = (TextBox)row.FindControl("txt_BillDueDate");
TextBox billingdate = (TextBox)row.FindControl("txt_BillGenDate");
TextBox remarks = (TextBox)row.FindControl("txtOthers");
//Update Bill Data Procedure
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetStoredProcCommand("sp_Update_GenBill");
db.AddInParameter(cmd, "#gridrowID", System.Data.DbType.Int32);
db.SetParameterValue(cmd, "#gridrowID", billgenID);
db.AddInParameter(cmd, "#bmonth", System.Data.DbType.String, 3);
db.SetParameterValue(cmd, "#bmonth", ddmonths.SelectedValue);
//Execute Stored Procedure
int i = 0;
i = db.ExecuteNonQuery(cmd);
if (i != 0)
{
showalert("Succesfuly Updated...");
}
else
showalert("Error occured while updating...");
}
}
}
My guess is your last postback before each refresh was a control with a command associated with it. When you hit REFRESH in your browser, it actually reposts the command. Try just going to your browser's address field and hitting ENTER. Do you get the same results?

Resources