how could i collect all the radio button that chosen in submit button? - asp.net

Here is my Code:
public partial class Play : System.Web.UI.UserControl
{
int surveyId = 153;
protected void Page_Load(object sender, EventArgs e)
{
// surveyId = int.Parse(Request[SurveyContext.SurveyID]);
FillQuestion();
}
void FillQuestion()
{
IList<Eskadenia.Framework.Survey.Entitis.Question> QuestionLst = Eskadenia.Framework.Survey.Data.QuestionManager.GetQuestionBySurveyId(surveyId);
try
{
RepPlay.DataSource = QuestionLst;
RepPlay.DataBind();
}
catch (Exception ex)
{
Response.Write(ex.InnerException);
}
}
protected void RepPlay_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RadioButtonList rblAnswers = ((RadioButtonList)e.Item.FindControl("rblAnswers"));
IList<Eskadenia.Framework.Survey.Entitis.Answer> answerlst;
answerlst = Eskadenia.Framework.Survey.Data.AnswerManager.GetAnswerByQuestionID(((Eskadenia.Framework.Survey.Entitis.Question)(e.Item.DataItem)).ID);
for (int i = 0; i < answerlst.Count; i++)
{
rblAnswers.Items.Add(new ListItem(answerlst[i].Name, answerlst[i].ID.ToString()));
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Redirect("~/Surveys.aspx");
}
}

First: you should databind the repeater only if(!IsPostBack):
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
FillQuestion();
}
Otherwise all changes are lost and events aren't triggered.
According to the core issue how to get all selected ListItems in the repeater, is this helpful:
var allSelectedItems = RepPlay.Items.Cast<RepeaterItem>()
.Select(ri => new{
ItemIndex = ri.ItemIndex,
SelectedItem = ((RadioButtonList) ri.FindControl("rblAnswers"))
.Items.Cast<ListItem>()
.First(li => li.Selected)
});
This presumes that you want the ItemIndex as identifier, if you need the ID you have to tell us where it's stored. You could also use ri.FindControl("HiddenIDControl") to get it.
Since you have commented that you want a dictionary, you could use this query:
Dictionary<int, string> questionAnswers = RepPlay.Items.Cast<RepeaterItem>()
.ToDictionary(ri => ri.ItemIndex, ri => ((RadioButtonList)ri.FindControl("rblAnswers"))
.Items.Cast<ListItem>()
.First(li => li.Selected).Value);
Here is the same without LINQ, you're right, in this case the loop is even simpler:
Dictionary<int, string> questionAnswers = new Dictionary<int, string>();
foreach (RepeaterItem item in RepPlay.Items)
{
string selectedValue = ((RadioButtonList)item.FindControl("rblAnswers")).SelectedValue;
questionAnswers.Add(item.ItemIndex, selectedValue);
}
I have noticed that my LINQ approaches were too complicated anyway, you can always use RadioButtonList.SelectedValue since a RadioButtonList doesn't support multi-selection.

Related

unable to persist data on postback in dotnetnuke7

I have my website running on dotnetnuke 7.4, i have a checklistbox which i bind on the page load, and after selecting items from it, user clicks on the submit button, the selected items should save in database, however when i click on the submit button, checklistbox gets blank, i tried to enable ViewState at :
Web.config level
Page Level
Control Level
But all in vain, it still unbinds checklistbox because of which everything disappears, i tried the same in plain .net and it works like a charm.
Is there any specific settings in dotnetnuke to support viewstate, or is there any other better option to achieve this.
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in chkBox.Items)
Response.Write(item.Text + "<br />");
}
There's the issue. Remove that (!IsPostBack) check in your page_load event. Have your code to be like below. Else, only at first page load you are binding the datasource to control which gets lost in postback.
protected void Page_Load(object sender, EventArgs e)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
OR, to be more efficient; refactor your code to a method like below and store the data object in Session variable like
private void GetDataSource()
{
List<Entities> obj = null;
if(Session["data"] != null)
{
obj = Session["data"] as List<Entities>;
}
else
{
Entities objEntities = new Entities();
obj = objEntities.GetList(2);
}
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
Session["data"] = obj;
}
Call the method in your Page_Load event like
protected void Page_Load(object sender, EventArgs e)
{
GetDataSource();
}

PageIndexChanging Event in search button in asp.net?

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grid();
}
}
protected void btnsearch_Click(object sender, EventArgs e)
{
objRetailPL.ZoneName = ddlzone.SelectedValue;
//IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
//String datetime = txtdate.Text.ToString();
//DateTime dt = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
//objRetailPL.date =dt;
DataTable dtsearch = new DataTable();
dtsearch = objRetailBAL.searchzone(objRetailPL);
GVRate.DataSource = dtsearch;
GVRate.DataBind();
}
protected void GVRate_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GVRate.PageIndex = e.NewPageIndex;
grid();
}
catch (Exception ex)
{
}
}
I have this code for searching records.And for that grid i added page index,but it is not coming properly.When click on search button it is showing more n of records at that time page index is not working. It is calling First grid before clicking search button..How can I change my code please help me.....
Try this ...
private void grid()
{
if(!string.IsNullOrEmpty(yourSearchTextBox.Text)
{
// Then call search method. Make sure you bind the Grid in that method.
}
else
{
// Normally Bind the Grid as you are already doing in this method.
}
}
you have to check whether there is any search Text or not in that grid() method like...

radcombobox always selecting top item on postback

I have an edit page where I set the selected index of a radcombobox (rcb_ParentCompany) based on a value returned from the database. However on postback the text in the combobox keeps changing to the top item in the dataset. Any ideas why?
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
BindOperatingNameComboBox(rcb_OperatingName);
BindParentCompanyComboBox(rcb_ParentCompany);
}
}
protected void btn_Edit_Command(object sender, CommandEventArgs e)
{
Client ClientToEdit = ClientController.ViewClient(int.Parse(e.CommandArgument.ToString()));
//Populate Client fields
txt_ClientName.Text = ClientToEdit.ClientName;
rcb_OperatingName.Text = ClientToEdit.OperatingName;
int ParentCompanyIndex = rcb_ParentCompany.FindItemIndexByValue(ClientToEdit.ParentCompanyID.ToString());
rcb_ParentCompany.SelectedIndex = ParentCompanyIndex;
txt_Address1.Text = ClientToEdit.Address1;
txt_Address2.Text = ClientToEdit.Address2;
txt_Country.Text = ClientToEdit.Country;
txt_Region.Text = ClientToEdit.Region;
txt_City.Text = ClientToEdit.City;
txt_PostalCode.Text = ClientToEdit.PostalCode;
txt_ClientNote.Text = ClientToEdit.ClientNote;
tbl_EditServices.Controls.Clear();
PopulateEditClientPanel(ClientToEdit);
btn_SaveChanges.CommandArgument = e.CommandArgument.ToString();
btn_Cancel.CommandArgument = e.CommandArgument.ToString();
}
protected void BindParentCompanyComboBox(RadComboBox ComboBox)
{
DataTable OperatingNames = ClientController.GetExistingClientAndOperatingNames("");
ComboBox.DataTextField = "ClientName";
ComboBox.DataValueField = "ClientID";
ComboBox.DataSource = OperatingNames;
ComboBox.DataBind();
}
protected void rcb_ParentCompany_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
BindParentCompanyComboBox((sender as RadComboBox));
}
Any ideas why?
Yes, because you are doing if(IsPostBack) as opposed to if(!IsPostBack)

How to get all TextBox values from Repeater that contains UserControls?

I have one TextBox inside a UserControl, and this UserControl is repeating inside Repeater.
But, when user fills TextBox with values and after that I can't get values from TextBoxs.
default.aspx:
protected void Page_Load(object sender, EventArgs e)
{
//filling repeater with dataset
Repeater1.DataSource = ds;
Repeater1.DataBind();
}
On button1 click I'm trying to fill List<string> with values from textbox.texts
protected void Button1_Click(object sender, EventArgs e)
{
List<string> sss = new List<string>();
foreach (Control i in Repeater1.Controls)
{
foreach (Control item in i.Controls)
{
if (item is WebUserControl1)
sss.Add(((WebUserControl1)item).getString);
}
}
}
And UserControl code:
public string getString
{
get
{ return TextBox1.Text; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
you should loop on all repeater's items and use FindControl to find your user control then call the getString method on such found instances, pseudo-code (not tested):
foreach(var rptItem in Repeater1.Items)
{
WebUserControl1 itemUserControl = ((WebUserControl1)rptItem .FindControl("WebUserControl1"))
if(itemUserControl != null)
{
var itemText = itemUserControl.getString();
}
}

How to preserve dynamically created controls?

I want to preserve the dynamically created control when postback occurs .
protected void Page_Load(object sender, EventArgs e)
{
}
private void CreateTable()
{
HtmlTableRow objHtmlTblRow = new HtmlTableRow();
HtmlTableCell objHtmlTableCell = new HtmlTableCell();
objHtmlTableCell.Controls.Add(new TextBox());
objHtmlTblRow.Cells.Add(objHtmlTableCell);
mytable.Rows.Add(objHtmlTblRow);
this.SaveControlState();
// this.Controls.Add(mytable);
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateTable();
}
It can be achieved by calling CreateTable() in Page_Load. Is there any alternative way to preserve the control
Thanks
You can add them to a List when you create them and save your List to Session. On postback (Page_Load) load them from your Session to your Page.
the below code should work
protected void Page_PreInit(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
CreateTable()
}
public static Control GetPostBackControl(Page thisPage)
{
Control ctrlPostedback = null;
string ctrlName = thisPage.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
{
ctrlPostedback = thisPage.FindControl(ctrlName);
}
else
{
foreach (string Item in thisPage.Request.Form)
{
Control c = thisPage.FindControl(Item);
if (((c) is System.Web.UI.WebControls.Button))
{
ctrlPostedback = c;
}
}
}
return ctrlPostedback;
}
The code works from UpdatePanel
Reference:http://www.asp.net/ajax/videos/how-to-dynamically-add-controls-to-a-web-page

Resources