How to get all TextBox values from Repeater that contains UserControls? - asp.net

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

Related

how could i collect all the radio button that chosen in submit button?

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.

GridView Editing when bound to a Datatable (no database)

I am a beginner at ASP.NET and I have been trying to allow editing/updating of a GridView that is bound to a Datatable, without apparent success.
The GridView, named "WeightGridView", has two columns, "Asset Class" and "Weight", and is populated upon the click of a button "AddAssetsButton". Once you click on this button, the GridView will be populated with the values of a listbox, "ListBox2". The code for this event handler is:
protected void AddAssetsButton_Click(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("Asset Class", typeof(string));
table.Columns.Add("Weight", typeof(double));
foreach (ListItem li in ListBox2.Items)
{
DataRow dr = table.NewRow();
dr["Asset Class"] = li.Value;
dr["Weight"] = 0;
table.Rows.Add(dr);
}
WeightGridView.DataSource = table;
WeightGridView.DataBind();
SelectAssetsButton_ModalPopupExtender.Hide();
}
I have created a RowEditing and RowUpdating functions for the GridView, but they don't seem to work properly.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
WeightGridView.DataBind();
}
}
protected void WeightGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
WeightGridView.EditIndex = e.NewEditIndex;
}
protected void WeightGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string weight;
weight = ((TextBox)WeightGridView.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
WeightGridView.EditIndex = -1;
WeightGridView.DataBind();
}
Should you need any additional code to answer this post, please let me know and I will update the post.
Any help will be appreciated! Thank you!

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

asp.net making a gridView column invisible

This is a Master-Detail form. Master is a GridView. And, the Detail is a DetailsView.
The entire thing is achieved programmatically.
As you can see from the code, DetailsView is using the Master-objects's ID to retrieve the Detail items.
I need to make the ID column of the Master-GridView invisible. Coz, it is irrelevent for the user of the page. But it must not harm the page logic.
But the code-line, GridView1.Columns[1].Visible = false; is generating an exception.
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How should I solve this problem?
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
List<Order> orders = Order.Get();
GridView1.DataSource = orders;
GridView1.DataBind();
// This is giving Error...............!!!
GridView1.Columns[1].Visible = false;
// At first, when the page first loads,
// GridView1.SelectedIndex == -1
// So, this is done to automatically select the 1st item.
if (GridView1.SelectedIndex < 0)
{
GridView1.SelectedIndex = 0;
}
int selRowIndex = GridView1.SelectedIndex;
int selMasterId = Convert.ToInt32(GridView1.Rows[selRowIndex].Cells[1].Text);
Order master = Order.Get(selMasterId);
labItemsCount.Text = master.Items.Count.ToString();
DetailsView1.DataSource = master.Items;
DetailsView1.DataBind();
}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
BindData();
}
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
{
DetailsView1.PageIndex = e.NewPageIndex;
BindData();
}
}
Have you considered using the DataKeyNames property of the gridview? This way you can remove the 'id' column from the GridView bu still access the 'id' value in the Page_Load.
DataKeyNames = "id"
Then you can get the value of the id like this.
int selRowIndex = GridView1.SelectedIndex;
int selMasterId = Convert.ToInt32(GridView.DataKeys[selRowIndex].Value);
Order master = Order.Get(selMasterId);
Alternately, you could try changing the visibility of the column in the OnRowBound event of the GridView.
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header ||
e.Row.RowType == DataControlRowType.DataRow ||
e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].Visible = false;
}
}

CheckedChanged event for Dynamically generated Checkbox column in DataGrid(Asp.Net)

I have a datagrid (Asp.Net) with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..
Here is my code:
public class ItemTemplate : ITemplate
{
//Instantiates the checkbox
void ITemplate.InstantiateIn(Control container)
{
CheckBox box = new CheckBox();
box.CheckedChanged += new EventHandler(this.OnCheckChanged);
box.AutoPostBack = true;
box.EnableViewState = true;
box.Text = text;
box.ID = id;
container.Controls.Add(box);
}
public event EventHandler CheckedChanged;
private void OnCheckChanged(object sender, EventArgs e)
{
if (CheckedChanged != null)
{
CheckedChanged(sender, e);
}
}
}
and Here is the event
private void OnCheckChanged(object sender, EventArgs e)
{
}
Thanks In advance
When do you add your custom column? If it is on load, then it is too late. Load it on init. I.e. following works with your code:
protected void Page_Init(object sender, EventArgs e)
{
ItemTemplate myTemplate = new ItemTemplate();
myTemplate.CheckedChanged += new EventHandler(myTemplate_CheckedChanged);
TemplateField col = new TemplateField();
col.ItemTemplate = myTemplate;
col.ItemStyle.Wrap = false;
grid.Columns.Add(col);
}
If your checkbox ID's are not being set the same way on every postback, then they can never be connected to the event handlers when it comes time to process the events. Where is your field "id" coming from?

Resources