ASP.NET get all values of radiobuttonlist that in repeater? - asp.net

aspx file:
<asp:Repeater ID="Repeater_sorular" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<div class="div_soru">
<div class="div_soru_wrapper">
<%#Eval("Subject")%>
<asp:RadioButtonList ID="RadioButtonList_secenekler" runat="server" Visible='<%# Eval("TypeId").ToString() == "1" %>'
DataSource='<%#Eval("Secenekler")%>' DataTextField='<%#Eval("OptionName")%>' DataValueField='<%#Eval("OptionId")%>'>
</asp:RadioButtonList>
<asp:CheckBoxList ID="CheckBoxList_secenekler" runat="server" Visible='<%# Eval("TypeId").ToString() == "2" %>'
DataSource='<%#Eval("Secenekler")%>' DataTextField='<%#Eval("OptionName")%>' DataValueField='<%#Eval("OptionId")%>'>
</asp:CheckBoxList>
</div>
</div>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
and codebehind:
SpAnketDataContext db = new SpAnketDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeaterSorular();
}
}
protected void ImageButton_kaydet_OnCommand(object source, CommandEventArgs e)
{
}
private void BindRepeaterSorular()
{
int anket_id = 3;
var sorular = from soru in db.TableSurveyQuestions
where soru.SurveyId == anket_id
select new
{
soru.TypeId,
soru.Subject,
soru.QuestionId,
soru.SurveyId,
soru.QueueNo,
SurveyTitle = soru.TableSurvey.Title,
TypeName = soru.TableSurveyQuestionType.TypeName,
Secenekler = from secenekler in soru.TableSurveyOptions
select new
{
secenekler.OptionId,
secenekler.OptionName,
secenekler.QuestionId,
}
};
Repeater_sorular.DataSource = sorular;
Repeater_sorular.DataBind();
}
this is the code that I try to get values but I can get only last radiobuttonlist values.
protected void Repeater_sorular_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
foreach (RepeaterItem item in Repeater_sorular.Items)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
CheckBoxList CheckBoxList1 = (CheckBoxList)e.Item.FindControl("CheckBoxList_secenekler");
RadioButtonList RadioButtonList1 = (RadioButtonList)e.Item.FindControl("RadioButtonList_secenekler");
if (CheckBoxList1 != null)
{
foreach (ListItem li in CheckBoxList1.Items)
{
TableSurveyVote votes=new TableSurveyVote();
votes.MemberId=1;
votes.OptionId=Int32.Parse(li.Value);
db.TableSurveyVotes.InsertOnSubmit(votes);
db.SubmitChanges();
}
}
if (RadioButtonList1 != null)
{
foreach (ListItem li in RadioButtonList1.Items)
{
TableSurveyVote votes=new TableSurveyVote();
votes.MemberId=1;
votes.OptionId=Int32.Parse(li.Value);
db.TableSurveyVotes.InsertOnSubmit(votes);
db.SubmitChanges();
}
}
}
}
}
What is wrong?

You get the same results as you say on the comment because you do not use the populate from the foreach loop (the item) but use the same reference e.Item on the loop.

Related

Getting values of my childRepeater

I have 2 repeaters where the first one list the questions and the second one list multiple choice for that specific question.
However, there are some multiple choice(input type="radio") or Text(input type="text") anwers. Im trying to get the value of either one(radio) or the other(text).
<%# DataBinder.Eval(Container.DataItem,"Descricao")%>
<%-- Listagem de Respostas --%>
<asp:Repeater ID="uxRespList" runat="server" OnItemDataBound="uxRespList_ItemDataBound" OnItemCommand="uxRespList_ItemCommand">
<ItemTemplate>
<tr>
<td>
<div id="uxRespostaText" visible="false" runat="server">
<input type="text" id="uxRespostaDissertativa" placeholder="Resposta" style="width:1000px" ></input>
</div>
<div id="uxRespostaRadio" visible="false" runat="server">
<input type="radio" id="uxResposta" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "Descricao")%>'/><%# DataBinder.Eval(Container.DataItem, "Descricao")%>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Code Behind
protected void uxQuestList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater rptRespostas = (Repeater)(e.Item.FindControl("uxRespList"));
QuestionarioPergunta pergunta = (QuestionarioPergunta)e.Item.DataItem;
rptRespostas.DataSource = ctx.QuestionarioRespostas.Where(x => x.PergId == pergunta.Id).ToList();
PergId.Text = pergunta.Id.ToString();
rptRespostas.DataBind();
}
}
protected void uxRespList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Web.UI.HtmlControls.HtmlContainerControl uxRespostaText = (System.Web.UI.HtmlControls.HtmlContainerControl)e.Item.FindControl("uxRespostaText");
System.Web.UI.HtmlControls.HtmlContainerControl uxRespostaRadio = (System.Web.UI.HtmlControls.HtmlContainerControl)e.Item.FindControl("uxRespostaRadio");
int PerguntaID = Int32.Parse(PergId.Text);
var pergunta = ctx.QuestionarioPerguntas.Where(x => x.Id == PerguntaID).FirstOrDefault();
if (pergunta.TipoPergunta == "Dissertativa")
{
uxRespostaText.Visible = true;
}
else
{
uxRespostaRadio.Visible = true;
}
}
}
//Save here
protected void uxSalvarPesquisa_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in uxRespList.Items)
{
}
}
You can get values of your html input as below and based on your requirement you can modify the code.
foreach (RepeaterItem item in uxQuestList.Items)
{
Repeater uxRespList = (Repeater)item.FindControl("uxRespList");
foreach (RepeaterItem inneritem in uxRespList.Items)
{
HtmlInputText input = (HtmlInputText)inneritem.FindControl("uxRespostaDissertativa");
if (input.Attributes["visible"] == "true")
{
var answer = input.Value;
}
HtmlInputRadioButton inputRadio = (HtmlInputRadioButton)inneritem.FindControl("uxRespostaRadio");
if (inputRadio.Attributes["visible"] == "true")
{
var answer = inputRadio.Value;
}
}
}

RadGrid: Get the modified Items on edit

On a RadGrid I can use the CommandItemTemplate to define my own buttons for, in my case, Save and Cancel the edit (like below)
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server" CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server" CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
On the code behind, I set up the ItemCommand.
> protected void RadGrid1_ItemCommand(object sender, GridCommandEventArgs e)
{
if (e.CommandName.CompareTo("UpdateEdited") == 0)
{
var commandItem = ((GridCommandItem)e.Item);
//Updade code here.
}
}
How can I access the modified row with the modified fields so I can perform an updade?
You should have them in command item and you can access them like this:
GridDataItem item = (GridDataItem)e.Item;
string value = item["ColumnUniqueName"].Text;
Is this what you want ? Just a sample you might need to modify it..
.aspx
<telerik:RadGrid ID="rg" runat="server" AutoGenerateColumns="false"
OnNeedDataSource="rg_NeedDataSource" OnItemCommand="rg_ItemCommand"
MasterTableView-CommandItemDisplay="Top" OnItemDataBound="rg_ItemDataBound">
<MasterTableView EditMode="InPlace">
<CommandItemTemplate>
<div style="padding: 5px 5px;">
<asp:LinkButton ID="btnUpdateEdited" runat="server"
CommandName="UpdateEdited">Update</asp:LinkButton>
<asp:LinkButton ID="btnCancel" runat="server"
CommandName="CancelAll">Cancel editing</asp:LinkButton>
</div>
</CommandItemTemplate>
<Columns>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("A") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt" runat="server"
Text='<%# Eval("A") %>'></asp:TextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Text="Edit"
CommandName="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate> </EditItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
dt.Rows.Add("A1");
// Check & Bind
if (dt != null)
{
// Viewstate
ViewState["Data"] = dt;
rg.DataSource = dt;
rg.DataBind();
dt.Dispose();
}
}
}
protected void rg_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
protected void rg_ItemCommand(object sender, GridCommandEventArgs e)
{
// Check
if (e.CommandName == "UpdateEdited")
{
// Variable
DataTable dt = new DataTable();
dt.Columns.Add("A");
// Loop All
foreach (GridEditableItem item in rg.Items)
{
// Find Control
TextBox txt = item.FindControl("txt") as TextBox;
// Check & Add to DataTable
if (txt != null) dt.Rows.Add(txt.Text.Trim());
}
// Check
if (dt != null && dt.Rows.Count > 0)
{
// Set Viewstate
ViewState["Data"] = dt;
// Bind
rg.DataSource = dt;
rg.DataBind();
// Dispose
dt.Dispose();
}
}
else if (e.CommandName == "CancelAll")
{
// Clear Edit Mode
rg.MasterTableView.ClearChildEditItems();
// Rebind
rg.Rebind();
}
}
protected void rg_ItemDataBound(object sender, GridItemEventArgs e)
{
// Check
if (e.Item is GridCommandItem)
{
// Find Control
LinkButton btnUpdateEdited = e.Item.FindControl("btnUpdateEdited") as LinkButton;
LinkButton btnCancel = e.Item.FindControl("btnCancel") as LinkButton;
// Get is Edit Mode ?
if (rg.EditIndexes.Count > 0)
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = true;
if (btnCancel != null) btnCancel.Visible = true;
}
else
{
if (btnUpdateEdited != null) btnUpdateEdited.Visible = false;
if (btnCancel != null) btnCancel.Visible = false;
}
}
}

DropDownList's SelectedIndexChanged event calls all events

i'm using Asp .Net Web Forms. i have 2 dropDown list and 1 input field. I want when i change the item on the dropDown list or the field value to call some event but it calls all the events.
for example if i change size it calls Size_SelectedIndexChanged, then Color_SelectedIndexChanged, and then txtKolicina_TextChanged
if i change color it calls Color_SelectedIndexChanged, than Size_SelectedIndexChanged and then txtKolicina_TextChanged.
Any help?
<asp:DropDownList ID="Colors" runat="server" AutoPostBack="true" CssClass="form-control detal-page-input" Style="height: 30px;" OnSelectedIndexChanged="Colors_SelectedIndexChanged" AppendDataBoundItems="True" DataSourceID="LinqDataSource3" DataTextField="color" DataValueField="color" >
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="Size" runat="server" OnSelectedIndexChanged="Size_SelectedIndexChanged" AppendDataBoundItems="true" AutoPostBack="true" CssClass="form-control detal-page-input" Style="height: 30px;" DataSourceID="LinqDataSource2" DataTextField="size" DataValueField="size" EnableViewState="true">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
<asp:TextBox Name="txtKolicina" ID="txtKolicina" runat="server" CssClass="form-control form-numberone detal-page-input" OnTextChanged="txtKolicina_TextChanged" ></asp:TextBox>
this is backEnd
protected void Size_SelectedIndexChanged(object sender, EventArgs e)
{
//do something
}
protected void Colors_SelectedIndexChanged(object sender, EventArgs e)
{
//do something
}
protected void txtKolicina_TextChanged(object sender, EventArgs e)
{
//do something
}
UPDATE
public string[] GetColor()
{
CMS_Shop_ModuleDataContext db = new CMS_Shop_ModuleDataContext();
var color = (from p in db.CMS_Articles
where
p.articleID == int.Parse(HiddenFieldArticalId.Value) ||
p.sameAsArticleID == int.Parse(HiddenFieldArticalId.Value)
//where p.articleID == 10049 || p.sameAsArticleID == 10049
select p.color).Distinct();
return color.ToArray();
}
public int GetColorCount()
{
CMS_Shop_ModuleDataContext db = new CMS_Shop_ModuleDataContext();
var color = (from p in db.CMS_Articles
where (p.articleID == int.Parse(HiddenFieldArticalId.Value)
|| p.sameAsArticleID == int.Parse(HiddenFieldArticalId.Value))
&& p.color != ""
select p.color);
return color.Distinct().Count();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (GetColorCount() == 0)
{
Colors.Visible = false;
lblBoja.Visible = false;
}
else
{
Colors.Visible = true;
lblBoja.Visible = true;
}
Looks like you use View State and repopulate your DropDownLists in code behind on Postback. Can you show OnInit and OnLoad ?
Or just try this code:
if (!IsPostBack) {
// populate all drop downs lists
}
Ok i found what was the problem.
a change
EnableViewState="false"
to
EnableViewState="true"

Cascading DropdownList in Gridview in ASP.NET

I am going to implement a cascading DropDownList inside a GridView control. My code is given below:
Page:
<asp:GridView ID="GridView1" runat="server" Width="550px"
AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="State">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1"
AutoPostBack="true" runat="server" DataTextField="State" DataValueField="StateID" onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2"
AutoPostBack="true" runat="server" DataTextField="City" DataValueField="CityId">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
Code Behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl1 = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl1 != null)
{
using (var context = new ABCEntities())
{
var _state= from u in context.State
select new
{
StateId= u.StateId,
State= u.State
};
ddl1.DataSource =_state.ToList();
ddl1.DataValueField = "StateId";
ddl1.DataTextField = "State";
ddl1.DataBind();
ddl1.Items.Insert(0, new ListItem("--Select--", "0"));
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList ddl1 = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl1.NamingContainer;
if (row != null)
{
DropDownList ddl2 = (DropDownList)row.FindControl("DropDownList2");
ddl2.DataSource = GetDataForSecondDropDownList(Convert.ToInt32(ddl1.SelectedValue));
ddl2.DataTextField = "CityID";
ddl2.DataValueField = "City";
ddl2.DataBind();
}
}
public IEnumerable<City> GetDataForSecondDropDownList(int ID) //Getting Error
{
using (var context = new ABCEntities())
{
var _city = (from u in context.Cities
where u.StateID == ID
select new City
{
CityID = u.CityID,
City= u.City
}).Distinct();
return _city;
}
}
I am getting an error message : Error: Inconsistent accessibility: return type 'System.Collections.Generic.IEnumerable' is less accessible than method '.......GetDataForSecondDropDownList(int)'
what should i do please help me. Thanks in advance.
The error tells that City class is less accessible. Probably it is private or protected. Make sure you have declared it as public like this:
public class City
{
public int CityID {get;set;}
public string City {get;set;}
}

ASP.NET - Problem with GridView with Dynamic Columns

I have a GridView that includes BoundField and TemplateField elements. Some of the TemplateField elements are dynamically generated. For the sake of reference, here is the GridView that I am using
<asp:GridView ID="myGridView" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" ShowFooter="True" EnableModelValidation="True"
OnLoad="myGridView_Load" OnRowCommand="myGridView_RowCommand"
OnRowEditing="myGridView_RowEditing" OnRowDeleting="myGridView_RowDeleting"
OnRowCancelingEdit="myGridView_RowCancelingEdit"
OnRowUpdating="myGridView_RowUpdating">
<Columns>
<asp:BoundField DataField="Number" Visible="true" HeaderText="Test" />
<asp:TemplateField HeaderText="Number">
<EditItemTemplate>
<asp:TextBox ID="tb1" runat="server" Text='<%# Bind("Number") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lb1" runat="server" Text='<%# Bind("Number") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ftb" runat="server" Text="[x]" />
</FooterTemplate>
</asp:TemplateField>
<%-- Dynamically Generated Columns Will Be Inserted Here --%>
<asp:TemplateField HeaderText="Actions">
<EditItemTemplate>
<asp:LinkButton ID="ulb" runat="server" Text="update" CommandName="Update" />
<asp:LinkButton ID="clb" runat="server" Text="cancel" CommandName="Cancel" />
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="slb" runat="server" Text="insert"
OnClick="saveLinkButton_Click" />
</FooterTemplate>
<ItemTemplate>
<asp:LinkButton ID="elb" runat="server" Text="edit" CommandName="Edit" />
<asp:LinkButton ID="dlb" runat="server" Text="delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField
</Columns>
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0">
<tr><td>Number</td></tr>
<tr>
<td><asp:TextBox ID="ntb" runat="server" /></td>
<td><asp:LinkButton ID="slb2" runat="server" Text="save" OnClick="saveLinkButton_Click" /></td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
When the GridView initially loads, everything is loaded properly. However, anytime I perform a command (edit, insert, delete), all of the data goes away. Oddly, the BoundField values still appear correctly. However, any TemplateField does not seem to get rendered. The code that I am using to work with this GridView is here:
public partial class GridView : System.Web.UI.Page
{
private List<string> dynamicColumnNames = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
LoadPageData();
}
protected void saveLinkButton_Click(object sender, EventArgs e)
{
}
protected void myGridView_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
BindGridData();
}
}
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{ }
protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
{
myGridView.EditIndex = e.NewEditIndex;
BindGridData();
}
protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
LoadPageData();
BindGridData();
}
protected void myGridView_RowCancelingEdit(object sender, EventArgs e)
{
myGridView.EditIndex = -1;
BindGridData();
}
protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
myGridView.EditIndex = -1;
LoadPageData();
BindGridData();
}
private void BindGridData()
{
// Create a temporary data source
DataTable tempData = new DataTable();
tempData.Columns.Add("ID");
tempData.Columns.Add("Number");
// Dynamically add template columns
foreach (string columnName in dynamicColumnNames)
{
tempData.Columns.Add(columnName);
TemplateField templateField = new TemplateField();
templateField.HeaderTemplate = new MyTemplateField(ListItemType.Header, columnName);
templateField.ItemTemplate = new MyTemplateField(ListItemType.Item, columnName);
templateField.EditItemTemplate = new MyTemplateField(ListItemType.EditItem, columnName);
templateField.FooterTemplate = new MyTemplateField(ListItemType.Footer, columnName);
myGridView.Columns.Insert(2, templateField);
}
// Add some phony data
Random random = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < 10; i++)
{
DataRow tempRow = tempData.NewRow();
tempRow["Number"] = (i + 1);
foreach (string column in dynamicColumnNames)
tempRow[column] = random.NextDouble();
tempData.Rows.Add(tempRow);
}
// Bind the data to the grid
myGridView.DataSource = tempData;
myGridView.DataBind();
}
private void LoadPageData()
{
dynamicColumnNames.Add("USA");
dynamicColumnNames.Add("Japan");
dynamicColumnNames.Add("Mexico");
}
}
internal class MyTemplateField : ITemplate
{
// The type of the list item
private ListItemType listItemType;
// The value to use during instantiation
private string value1 = string.Empty;
public MyTemplateField(ListItemType listItemType, string value1)
{
this.listItemType = listItemType;
this.value1 = value1;
}
public void InstantiateIn(Control container)
{
if (listItemType == ListItemType.Item)
{
TextBox textBox = new TextBox();
textBox.ReadOnly = true;
textBox.DataBinding += new EventHandler(textBox_DataBinding);
container.Controls.Add(textBox);
}
else if (listItemType == ListItemType.EditItem)
{
TextBox textBox = new TextBox();
textBox.DataBinding += new EventHandler(textBox_DataBinding);
container.Controls.Add(textBox);
}
else if (listItemType == ListItemType.Header)
{
Literal literal = new Literal();
literal.Text = value1;
container.Controls.Add(literal);
}
else if (listItemType == ListItemType.Footer)
{
TextBox textBox = new TextBox();
container.Controls.Add(textBox);
}
}
private void textBox_DataBinding(object sender, EventArgs e)
{
TextBox textBox = (TextBox)(sender);
GridViewRow row = (GridViewRow)(textBox.NamingContainer);
textBox.Text = DataBinder.Eval(row.DataItem, value1).ToString();
}
}
How do I use commands in a GridView with Dynamically added columns? What is wrong with my code?
Thank you!
Dynamically added controls must be added on each post, you can't just add these controls on the first page load. Try removing your BindGridData() from within the Page.IsPostBack == false.

Resources