Good morning .
I search many times before posting here .
I am working on a project like a survey [Questions and Answers]
I am able to get all questions in datalist , now i am searching a way to display the answers in Radio button list inside each question .
here is page load
protected void Page_Load(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["TMConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
//Getting All Questions
SqlDataAdapter dr = new SqlDataAdapter("select * from Question ", con);
DataSet ds = new DataSet();
dr.Fill(ds, "Qs");
OuterDataList.DataSource = ds.Tables["Qs"];
OuterDataList.DataBind();
}
here is page body
<body>
<form id="form1" runat="server">
<h1>Test Page</h1>
<asp:DataList ID="OuterDataList" RunAt="server">
<ItemTemplate>
<h4><%# DataBinder.Eval (Container.DataItem, "Question") %></h4>
<asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList>
</ItemTemplate>
</asp:DataList>
</form>
i dont know how to bind radiobuttonlist and group the answers .
note : the common column between Question table and Answer table is Question_id
Firt will make a template like below.
<asp:DataList runat="server" ID="DataList1" RepeatDirection="Vertical"
DataKeyField="QuestionID" onitemdatabound="DataList1_ItemDataBound">
<ItemTemplate>
<table>
<tr>
<td>
<%# Eval("Question") %>
</td>
</tr>
<tr>
<td>
<asp:RadioButtonList runat="server" ID="RadioButtonList1">
</asp:RadioButtonList>
</td>
</tr>
</table>
</ItemTemplate>
After that using DataList1_ItemDataBound you can bind your answers.
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
RadioButtonList RadioButtonList1 = (RadioButtonList)e.Item.FindControl("RadioButtonList1");
//Get questionID here
int QuestionID = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "QuestionID"));
//pass Question ID to your DB and get all available options for the question
//Bind the RadiobUttonList here
}
}
Related
I am binding an ASP Repeater from List & trying to add paging in the repeater. Each Page would have 5 Rows. when The Page is Run, 5 items are visible fine but when I click on "2" link button, nothing is visible. When I again Click on "1" the items of Page 2 are visible.
I've gone through this to implement Paging.
Here is my aspx Code:
<asp:Repeater ID="rp_Order" runat="server" OnItemDataBound="rp_Order_ItemDataBound">
<HeaderTemplate>
<table class="table table-responsive">
<tr >
<th style="width:20%;">Data</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<h5 style="font-weight:bold; "><%# Eval("NewsSubject") %></h5>
<p><%# Eval("NewsDate") %></p>
<img src="ImageHandler.ashx?newsid=<%# Eval("NewsID") %>" visible="<%#Eval("ImageAttachment")!=null && Eval("ImageAttachment").ToString()!=""? "true": "false" %>" class="images image-responsive myimg" />
<p ><%# System.Web.HttpUtility.HtmlDecode(Eval("NewsDescription").ToString()) %></p>
<iframe src="<%#GetUrl(Eval("youtubeurl").ToString()) %>" width="400" frameborder="0" visible="<%#Eval("youtubeurl")!=null? "true": "false" %>'"></iframe>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lnkPage"
Style="padding: 8px; margin: 2px; background: lightgray; border: solid 1px #666; color: black; font-weight: bold"
CommandName="Page" CommandArgument="<%# Container.DataItem %>" runat="server" Font-Bold="True"><%# Container.DataItem %>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
Here is my Cs Code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
public void BindData()
{
List<tblLatestNew> lst_news = new List<tblLatestNew>();
lst_news = obj_news.GetLatestNews();
DataTable dtData = Utilities.ToDataTable(lst_news);
PagedDataSource pdsData = new PagedDataSource();
DataView dv = new DataView(dtData);
pdsData.DataSource = dv;
pdsData.AllowPaging = true;
pdsData.PageSize = 5;
if (ViewState["PageNumber"] != null)
pdsData.CurrentPageIndex = Convert.ToInt32(ViewState["PageNumber"]);
else
pdsData.CurrentPageIndex = 0;
if (pdsData.PageCount > 1)
{
Repeater1.Visible = true;
ArrayList alPages = new ArrayList();
for (int i = 1; i <= pdsData.PageCount; i++)
alPages.Add((i).ToString());
Repeater1.DataSource = alPages;
Repeater1.DataBind();
}
else
{
Repeater1.Visible = false;
}
rp_Order.DataSource = pdsData;
rp_Order.DataBind();
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
ViewState["PageNumber"] = Convert.ToInt32(e.CommandArgument);
BindData();
}
Please Help me resolving this!
Currently my table has 7 Rows, so Page 1 should have 5 rows and Page 2 must have 2 Rows
Thanks in Advance
The PagedDataSource requires a page index, which starts at zero for page 1. When you change the page in Repeater1_ItemCommand the command argument is the page number, not the page index.
To get the page index just change your code in Repeater1_ItemCommand so that you subtract 1 from whatever number is passed in via e.CommandArgument, that way the proper page will display
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
ViewState["PageNumber"] = Convert.ToInt32(e.CommandArgument) - 1;
BindData();
}
I have a nested repeater on my page like:
Aspx page:
<asp:Repeater ID="parentRepeater" runat="server">
<ItemTemplate>
<br />
<b><%# DataBinder.Eval(Container.DataItem,"question") %></b><br>
<!-- start child repeater -->
<asp:Repeater ID="childRepeater" DataSource='<%# ((DataRowView)Container.DataItem).Row.GetChildRows("relation") %>'
runat="server">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnCommand="LinkButton1_Command" CommandName="MyUpdate" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "[\"AnsId\"]")%>'><%# DataBinder.Eval(Container.DataItem, "[\"Ans\"]")%></asp:LinkButton>
<br>
</ItemTemplate>
</asp:Repeater>
<!-- end child repeater -->
</ItemTemplate>
</asp:Repeater>
Code behind:
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["star_report_con"].ConnectionString);
SqlDataAdapter cmd1 = new SqlDataAdapter("select questionId, question from questions", cnn);
//Create and fill the DataSet.
DataSet ds = new DataSet();
cmd1.Fill(ds, "questions");
//Create a second DataAdapter for the Titles table.
SqlDataAdapter cmd2 = new SqlDataAdapter("SELECT AnsId, Ans, questionId FROM answers", cnn);
cmd2.Fill(ds, "answers");
//Create the relation bewtween the Authors and Titles tables.
ds.Relations.Add("relation",
ds.Tables["questions"].Columns["questionId"],
ds.Tables["answers"].Columns["questionId"]);
//Bind the Authors table to the parent Repeater control, and call DataBind.
parentRepeater.DataSource = ds.Tables["questions"];
Page.DataBind();
//Close the connection.
cnn.Close();
protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
if (e.CommandName == "MyUpdate")
{
//e.CommandArgument --> contain the Ansid value
//I want to also find which questions ans is clicked i.e the questionId
}
}
In my child repeater I have a linkbutton on click of which i need to do some computaion for which I need to know which questions answers wa being clicked. i.e in my LinkButton1_Command I want to fetch the AnsId along with QuestionId.
How will I get parent repeaters Id in button click event?
Try this ,
<%# ((RepeaterItem)Container.Parent.Parent).DataItem %>
If this does not work then try
<%# DataBinder.Eval(Container.Parent.Parent, "DataItem.YourProperty")%>
if you're in code-behind in the ItemDataBound method:
((Repeater)e.Item.NamingContainer.NamingContainer).DataItem
I have a modalpopypextender that contains a grid view and I want populate it on button click which does this:
protected void btnViewRecipients_Click(object sender, EventArgs e)
{
ModalPopupExtender1.Show();
BindData();
}
Which is straight forward. BindData does this:
protected void BindData()
{
try
{
SqlCommand sqlCommand = new SqlCommand();
string connectionString = "Data Source=SERVER\\DB1;Initial Catalog=Survey;User ID=abcde;Password=12345;";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlCommand = sqlConnection.CreateCommand();
sqlCommand.CommandText = "Select * From [Survey].[dbo].[data]";
SqlDataAdapter sda = new SqlDataAdapter(sqlCommand.CommandText, connectionString);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
//Create a DataTable to hold the query results.
//Fill the DataTable.
sda.Fill(dTable);
//Set the DataGridView DataSource.
gvRecords.DataSource = dTable;
gvRecords.DataBind();
sqlConnection.Close();
}
}
catch (SqlException ex)
{
//Console.WriteLine(ex.StackTrace);
}
}
Now this all works good and I get to see the grid with data. I then turned on autopaging and went ahead to create the call gvRecords_PageIndexChanged. I have also turned on EnableSortingAndPagingCallbacks.
protected void gvRecords_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvRecords.PageIndex = e.NewPageIndex;
gvRecords.DataSource = dTable;
gvRecords.DataBind();
}
This kinda works very strangely. I noticed that when I click a page number, the table becomes blank and shows me EmptyDataText that I defined earlier. But when I close the ModalPopupExtender and open it again (clicking the button again) it shows me the right page and data! e.g. if I clicked page 3, then get a blank table, now reopening the MPE will show me page 3's contents in a gridview. I guess that's the viewstate stored somewhere but why is it that the gridview will not show me the page right away?
I am really stuck at this and failing to understand what I'm missing!
Any help appreciated million times, I have searched and searched online for this but maybe it is so trivial and obvious that no one has ever needed to ask!?!
Edited I've been working with Modals, UpdatePanels and ListViews for years, we'll solve this, but it would be good to see the entire markup.
From your comments I'd suggest;
Put your entire modal markup in the UpdatePanel. Make sure to set the ID and UpdateMode to conditional;
<asp:UpdatePanel ID="upModal" runat="server" UpdateMode="Conditional">
<ContentTemplate>
</ContentTemplate>
</asp:UpdatePanel>
I usually use an ASP:Panel as my DIV inside my update panel;
<asp:Panel ID="pnlPopup" runat="server" CssClass="ModalPanel">
Then place your GridView (or in my case ListView) in your panel
In your code behind after you call your gvRecords.Databind(), call upModal.Update()
protected void gvRecords_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvRecords.PageIndex = e.NewPageIndex;
gvRecords.DataSource = dTable;
gvRecords.DataBind();
upModal.Update();
}
I got it working finally, I have had to set PopupControlID to upModal, the updatepanel's ID, as opposed to the inner panel. The targetcontrolID also had to point to a hidden button, as many have found you must when working with MPEs...
Anyway, here goes:
<asp:Button ID="hiddenButton" runat="server" Text="" style="display:none;" />
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server" Enabled="True" TargetControlID="hiddenButton" PopupControlID="upModal" BehaviorID="modalbehavior" BackgroundCssClass="modalBackground" OnCancelScript="cancelClick();" CancelControlID="closePopup">
</ajaxToolkit:ModalPopupExtender>
<asp:UpdatePanel runat="server" ID="upModal" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel id="pnlPopup" runat="server" class="ModalPanel" >
<table cellpadding="5" cellspacing="5" class="topBanner" style="width:100%;">
<tr>
<td width="50">
<asp:LinkButton ID="closePopup" runat="server" onclick="LinkButton1_Click" CssClass="ClosePopupCls">Close
[x]</asp:LinkButton>
</td>
<td align="center">
<asp:Label ID="lbl" runat="server" Text="Status"></asp:Label>
</td>
<td width="25">
</td>
</tr>
<tr>
<td colspan="3">
<asp:GridView ID="gvRecords" runat="server" AllowPaging="True"
BackColor="White" EmptyDataText="No Record Found"
EnableSortingAndPagingCallbacks="True" ForeColor="GrayText" Height="600"
onpageindexchanging="gvRecords_PageIndexChanging" Width="800">
</asp:GridView>
</td>
</tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
I am using ASP.NET, C#, Sql Server 2005 for my project and
I'm using the repeater control to form a table of users that are a member of a site and a button next to each user so that they can be added to your friends list. I have everything set up except I dont know how to get the specific info of each row after a button click. I mean,
How to send a friend request to a person whose username is displayed besides the button? or
How to access the the displayed username besides the button so that I can use it for my code?
My Script
<asp:Repeater ID="myrepeater" runat="server">
<HeaderTemplate>
<table style="font: 8pt verdana">
<tr style="background-color:#3C78C3">
<th>Search Result</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%#DataBinder.Eval(Container,"DataItem.allun")%>
<asp:Button ID="Button1" runat="server" Text="Button" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
Code Behind
protected void btnSearch_Click(object sender, EventArgs e)
{
con.Open();
if (txtSearch.Text != "")
{
SqlDataAdapter mycommand = new SqlDataAdapter("select * from WebAdminTable where allun='" + txtSearch.Text + "'", con);
DataSet ds = new DataSet();
mycommand.Fill(ds);
myrepeater.DataSource = ds;
myrepeater.DataBind();
}
else
{
//msgbox for entering value
}
con.Close();
}
protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
//?
}
You can bind the userName to a label control and then you can access the value of the label control on the click of button like...
protected void btnAddToMyFList_Click(object sender, EventArgs e)
{
Button btnAddToMyFList = (Button)sender;
Label label = (Label)btnAddToMyFList.Parent.FindControl("LabelId");
String labelText = label.Text; //userName of clicked row
}
I used repeater in asp.net. My problem is don't know how to hide a fields in repeater. There is a regular price and now price if regular price is equal to zero it will hide the fields and if not it will show the value of the regular price. i hope you can help on this.
here my code in asp:
<a href="<%=Utility.GetSiteRoot() %>/BookInfo.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>">
<img width="150px" src='<%# Eval("lb_picturepath")%>'>
</td>
<td valign="top">
<asp:Label ID="lb_titleLabel" runat="server" CssClass="center-head" Text='<%# Eval("lb_title") %>' />
<p><asp:Label ID="lb_descriptionLabel" runat="server" Text='<%# Eval("lb_description") %>' /></p>
<div class="price"><%# "Price: " + decimal.Round((decimal)Eval("lb_sellingprice"),2)%></div>
</td>
</tr>
<tr>
<td></td>
<td>
<a class="addtocart" href="<%=Utility.GetSiteRoot() %>/AddToCart.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>" >Add To Cart</a>
<a href="<%=Utility.GetSiteRoot() %>/BookInfo.aspx?SKU=<%# Utility.SKUMask(Eval("lb_sku").ToString()) %>" class="readmore">
View Details
</a></td>
thanks!
You would need to handle the OnItemDataBound event, and then change the visibility of the control. An example of this is shown below:
ASPX Page
<asp:Repeater ID="MyRepeater" OnItemDataBound="MyRepeater_OnItemDataBound" runat="server">
<ItemTemplate>
<asp:Label ID="RegularPriceLabel" runat="server" />
<br/>
<asp:Label ID="BuyNowPriceLabel" runat="server" />
</ItemTemplate>
</asp:Repeater>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyRepeater.DataSource = GetDataSource();
MyRepeater.DataBind();
}
}
protected void MyRepeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// This will be your data object
MyEntity o = (MyEntity) e.Item.DataItem;
// Get the labels
Label RegularPriceLabel = (Label) e.Item.FindControl("RegularPriceLabel");
Label BuyNowPriceLabel = (Label) e.Item.FindControl("BuyNowPriceLabel");
// Only show regular price if it is set
RegularPriceLabel.Visible = (o.RegularPrice > 0);
// Populate labels
RegularPriceLabel.Text = o.RegularPrice.ToString();
BuyNowPriceLabel.Text = o.BuyNowPrice.ToString();
}
}
I would take a look at the ItemDataBound event of the Repeater. It will fire for every item in the repeater and allow you to do any code-behind (like hiding labels) more easily.
Edit: For your specific example, since you are formatting the price as well, it may be easier to just call a custom method to to render the price, like so:
ASPX:
<%#RenderPrice((decimal)Eval("lb_sellingprice"))%>
Method:
protected string RenderPrice(decimal price) {
if (price > 0) {
return "Price: $" + decimal.Round(price);
} else {
return string.Empty;
}
}
It's quick-and-dirty but it works.