I have issue with viewstate of dropdown list [duplicate] - 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.

DropDownList-Items are null on postback

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...
}
}

Dropdownlist in repeater control

I have 3 dropdownlist which will have set of values from the database. In my page, I have different controls. I was planning to add this dropdownlist in a repeater control.
When a user selects a value, the value will be saved to the database, either by a save button inside the control or automatically.
Could you please let me know if this is possible? If yes, any code that can be shared would be helpful.
Yes, it's possible. The trick is that the DataSource for the dropdownlists are separate than the DataSource of the Repeater.
Here's the sample code:
protected void cmdSave_Click(object sender, EventArgs e)
{
foreach (RepeaterItem ri in GeneralRepeater.Items)
{
switch (ri.ItemType)
{
case ListItemType.Item:
case ListItemType.AlternatingItem:
DropDownList GetValue = (DropDownList)ri.FindControl("GeneralDDL");
var sSelectedValue = GetValue.SelectedValue;
for (int index = 0; index <= PocDiagnoses.MAX_DIAGNOSIS; index++)
{
foreach (RepeaterItem ri1 in GeneralRepeater.Items)
{
int iItemIndex = ri1.ItemIndex;
DropDownList myDDL = (DropDownList)GeneralRepeater.Items[index].FindControl("GeneralDDL");
FirstPlanOfCare.Diagnoses.Diagnoses[index] = new PatientDiagnosis(myDDL.SelectedValue, new SynergyOnSetDate(new System.DateTime(Year, Month, Day)), "01/02/2011"); //Insert Diagnosis Value
}
}
break;
}
}
//Create
Chart.AddPlanOfCare(FirstPlanOfCare);
}

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