I am trying to create a dynamic Multiple-choice Question Quiz, where we have different categories in which there are multiple questions with their individual options. I need to store the selected option as per the user.
Below is the aspx code which I am using to bind the data:
<div id="contact-form">
<input type="text" class="form-control form-control-custom" tabindex="-1"
id="text-field" name="text-field">
<asp:ListView ID="lv_cat" runat="server" OnItemDataBound="lv_cat_ItemDataBound">
<EmptyDataTemplate></EmptyDataTemplate>
<ItemTemplate>
<h4 style="border: 2px solid #000; background-color: #ffd281;"><%# Eval("Cat_name") %></h4>
<asp:Label ID="lbl_Cat_id" runat="server" Text='<%# Eval("cat_id") %>' hidden="true"></asp:Label>
<asp:ListView ID="Lv_question" runat="server" OnItemDataBound="Lv_question_ItemDataBound">
<EmptyDataTemplate></EmptyDataTemplate>
<ItemTemplate>
<div class="row">
<p style="text-align: left; font-weight: 600;"><%# Eval("Question") %></p>
<asp:Label ID="lbl_Q_Id" runat="server" Text='<%# Eval("Q_id") %>' hidden="true"></asp:Label>
<asp:RadioButtonList ID="Rbl_options" runat="server" Style="text-align: left;">
</asp:RadioButtonList>
</div>
</ItemTemplate>
</asp:ListView>
</ItemTemplate>
</asp:ListView>
</div>
<!-- /End Contact Form -->
<br />
<!-- Submit Button -->
<div class="btn-row">
<div class="form-group">
<asp:Button ID="Button2" class="btn btn-dark" runat="server" Text=" Submit"></asp:Button>
</div>
</div>
And the below is the aspx.cs code for binding the data.
Now I want to fetch the details submitted by the user.
private void getProjectdetails()
{
try
{
BAL_Projects balprojects = new BAL_Projects();
balprojects.P_id = p_id;
ds = balprojects.get_data_By_project_Id(str);
if (ds.Tables[0].Rows.Count > 0)
{
lbl_Project.Text = ds.Tables[0].Rows[0]["pname"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void lv_cat_ItemDataBound(object sender, ListViewItemEventArgs e)
{
try
{
Label cat_id = (Label)e.Item.FindControl("lbl_Cat_id");
balQuestions = new BAL_Questions();
balQuestions.Cat_id = cat_id.Text;
ds1 = balQuestions.get_data_questions_By_category_ID(str);
ListView ListView2 = e.Item.FindControl("Lv_question") as ListView;
if (ds1.Tables[0].Rows.Count > 0)
{
ListView2.DataSource = ds1.Tables[0];
ListView2.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void Lv_question_ItemDataBound(object sender, ListViewItemEventArgs e)
{
try
{
Label Q_id = (Label)e.Item.FindControl("lbl_Q_Id");
BAL_options bal_options = new BAL_options();
ds = bal_options.get_options_for_Question(str, Q_id.Text.ToString());
if (ds.Tables[0].Rows.Count > 0)
{
RadioButtonList rbl_1 = (RadioButtonList)e.Item.FindControl("Rbl_options");
rbl_1.DataSource = ds;
rbl_1.DataTextField = "answers";
rbl_1.DataValueField = "A_id";
rbl_1.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
private void getCategorydata()
{
try
{
BAL_category bal_category = new BAL_category();
bal_category.p_id = p_id;
ds = bal_category.get_data_category_By_Project_ID(str);
if (ds.Tables[0].Rows.Count > 0)
{
lv_cat.DataSource = ds;
lv_cat.DataBind();
}
}
catch (Exception ex) { }
}
I also tried the below code:
public void btnsubmit_Click(object sender, EventArgs e)
{
try
{
foreach (ListViewItem item in lv_cat.Items)
{
ListView listQ = (ListView)item.FindControl("lv_Question");
foreach (ListViewItem item1 in listQ.Items)
{
Label QID = (Label)item1.FindControl("lbl_Q_Id");
RadioButtonList rbl1 = (RadioButtonList)item1.FindControl("rbl_options");
string test = rbl1.SelectedValue.ToString();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
You basically do the same as when you are binding data to the Rbl_options RadioButtonList in the ListView ItemDataBound. On the button click loop all the items in the ListView, locate the RadioButton within the item and use FindControl.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//bind the datasource for the listview
Lv_question.DataSource = source;
Lv_question.DataBind();
}
}
protected void Lv_question_ItemDataBound(object sender, ListViewItemEventArgs e)
{
//use findcontrol to locate the radiobuttonlist and cast is back
RadioButtonList rbl = e.Item.FindControl("Rbl_options") as RadioButtonList;
//add some dummy listitems
for (int i = 0; i < 3; i++)
{
rbl.Items.Add(new ListItem() { Text = "Item " + i, Value = i.ToString() });
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//loop all the items in the listview
foreach (var item in Lv_question.Items)
{
//use findcontrol again to locate the radiobuttonlist in the listview item
RadioButtonList rbl = item.FindControl("Rbl_options") as RadioButtonList;
//show results
Label1.Text += rbl.SelectedValue + "<br>";
}
}
The aspx to make the demo complete
<asp:ListView ID="Lv_question" runat="server" OnItemDataBound="Lv_question_ItemDataBound">
<ItemTemplate>
<asp:RadioButtonList ID="Rbl_options" runat="server"></asp:RadioButtonList>
</ItemTemplate>
</asp:ListView>
Related
I am creating a quiz application in ASP.net (c#) and I currently have one question at a time displaying with the use of a datapager. However, when i move from question 1 to question 2 and then back to question 1 the radiobutton selection disappears.
EDIT - I now have the radio button retaining a selection whenever I move from next to previous, HOWEVER, If I chose radiobutton1 and then move on to question 2, It has radiobutton1 already selected, even though I am yet to answer that question. So for some reason whatever selection I make on question 1 is being duplicated to the other questions.
Question1 example
Question2 example
<body>
<form id="form1" runat="server">
<div>
<asp:ListView ID="lvCustomers" runat="server" GroupPlaceholderID="groupPlaceHolder1"
ItemPlaceholderID="itemPlaceHolder1" OnPagePropertiesChanging="OnPagePropertiesChanging" OnPreRender="ListPager_PreRender">
<LayoutTemplate>
<div id="itemPlaceHolder1" runat="server">
</div>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="lvCustomers" PageSize="1">
<Fields>
<asp:NextPreviousPagerField runat="server" ButtonType="Link"
ShowFirstPageButton="false"
ShowPreviousPageButton="true"
ShowNextPageButton="false" />
<asp:NumericPagerField ButtonType="Link" />
<asp:NextPreviousPagerField ButtonType="Link"
ShowNextPageButton="true"
ShowLastPageButton="false"
ShowPreviousPageButton="false" />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("QuestionID")%>'></asp:Label><br />
<asp:Label ID="Label1" runat="server" Text='<%#Eval("QuestionText")%>'></asp:Label><br />
<li>
<asp:RadioButton ID="Radio1" Text='<%#Eval("Answer1") %>' GroupName="radiobtns" EnableViewState="true" runat="server" />
</li>
<li>
<asp:RadioButton ID="Radio2" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer2") %>' />
</li>
<li>
<asp:RadioButton ID="Radio3" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer3") %>' />
</li>
<li>
<asp:RadioButton ID="Radio4" runat="server" GroupName="radiobtns" EnableViewState="true" Text='<%#Eval("Answer4") %>' />
</li>
<br />
</ItemTemplate>
</asp:ListView>
</div>
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</p>
</form>
</body>
</html>
namespace WebApplication2.WebForms
{
public partial class _1QuestionQuiz : System.Web.UI.Page
{
string userAns;
int QuestionID;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindListView();
if (Session["QuizID"] != null)
{
int QuizID = Convert.ToInt32(Session["QuizID"]);
}
}
}
protected void ListPager_PreRender(object sender, EventArgs e)
{
if (Session["DTSource"] != null)
{
lvCustomers.DataSource = Session["DTSource"];
lvCustomers.DataBind();
}
GetSelections();
}
private void BindListView()
{
SqlConnection conn = new SqlConnection();
string connString = ConfigurationManager.ConnectionStrings["test1ConnectionString"].ConnectionString;
SqlCommand Cmd = new SqlCommand();
conn.ConnectionString = connString;
conn.Open();
if (lvCustomers != null)
{
foreach (ListViewItem item in lvCustomers.Items)
{
Label lbl = (Label)item.FindControl("Label2");
if (lbl != null)
{
QuestionID = Convert.ToInt32(lbl.Text);
ViewState["qstion"] = QuestionID;
}
RadioButton rd1 = (RadioButton)item.FindControl("Radio1");
RadioButton rd2 = (RadioButton)item.FindControl("Radio2");
RadioButton rd3 = (RadioButton)item.FindControl("Radio3");
RadioButton rd4 = (RadioButton)item.FindControl("Radio4");
if (rd1.Checked)
{
userAns = rd1.Text;
ViewState["Radio1"] = rd1.Text;
}
else if (rd2.Checked)
{
userAns = rd2.Text;
ViewState["Radio2"] = rd2.Text;
}
else if (rd3.Checked)
{
userAns = rd3.Text;
ViewState["Radio3"] = rd3.Text;
}
else if (rd4.Checked)
{
userAns = rd4.Text;
ViewState["Radio4"] = rd4.Text;
}
SqlCommand comm = new SqlCommand("InsertSelections", conn);
comm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(comm);
SqlParameter p1 = new SqlParameter("Answer", userAns);
SqlParameter p2 = new SqlParameter("QuestionID", QuestionID);
SqlParameter p3 = new SqlParameter("QuizID", (Session["QuizID"]));
comm.Parameters.Add(p1);
comm.Parameters.Add(p2);
comm.Parameters.Add(p3);
comm.ExecuteNonQuery();
}
}
}
private void GetSelections()
{
foreach (ListViewItem item in lvCustomers.Items)
{
Label lbl = (Label)item.FindControl("Label2");
if (lbl != null)
{
QuestionID = Convert.ToInt32(lbl.Text);
}
RadioButton rd1 = (RadioButton)item.FindControl("Radio1");
RadioButton rd2 = (RadioButton)item.FindControl("Radio2");
RadioButton rd3 = (RadioButton)item.FindControl("Radio3");
RadioButton rd4 = (RadioButton)item.FindControl("Radio4");
//Try radiobutton 1 as a tester
if (rd1 != null)
{
if (lbl != null && ViewState["Radio1"] != null)
{
rd1.Checked = true;
}
}
if (rd2 != null)
{
if (lbl != null && ViewState["Radio2"] != null)
{
rd2.Checked = true;
}
}
if (rd3 != null)
{
if (lbl != null && ViewState["Radio3"] != null)
{
rd3.Checked = true;
}
}
if (rd4 != null)
{
if (lbl != null && ViewState["Radio4"] != null)
{
rd4.Checked = true;
break;
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Score.aspx", false);
}
protected void OnPagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
(lvCustomers.FindControl("DataPager1") as DataPager).SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
BindListView();
}
}
}
Try overriding LoadViewState and SaveViewState to maintain the state of your radio buttons. For example, try something like the following, and pull the values back out of ViewState wherever you need them:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
if (ViewState["Radio1"] != null)
Radio1.Text = (int)ViewState["Radio1"];
...
}
protected override object SaveViewState()
{
ViewState["Radio1"] = Radio1.Text;
...
return base.SaveViewState();
}
I am loading a Datalist to create the necessary filters (textbox's,dropdown's,checkbox's) for a grid. So far so good, the problem is between postback's.
I understand that every time a postback occours I need to recreate the Datalist with the items, but how can I store the input made by the user on each control?
Imagine that I have created a textbox for filtering a column and the user input "test" on the textbox and click on button that triggers the event to search the value in the gridview.
How can I use (if so) the "viewstate" and when?
Here is the code
Client code:
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:PostBackTrigger ControlID="imgHelp" />
</Triggers>
<ContentTemplate>
<asp:Panel ID="pnlFilter" runat="server" Width="95%">
<asp:DataList ID="dlFilter" runat="server" RepeatColumns="4" RepeatDirection="Horizontal" OnItemDataBound="dlFilter_ItemDataBound" OnItemCreated="dlFilter_ItemCreated" EnableViewState="true">
<ItemTemplate>
<asp:HiddenField ID="hfFilterName" runat="server" Value='<%# Bind("szFilterName") %>' />
<asp:HiddenField ID="hfFilterType" runat="server" Value='<%# Bind("szFilterObjType") %>' />
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Bind("szFilterFiller") %>' />
</ItemTemplate>
<FooterTemplate>
<table>
<tr>
<td valign="middle" style="width: 120px; text-align: right;">
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Font-Names="Verdana" Font-Size="7pt" OnClick="btnSubmit_Click"
Text="Search" />
</td>
</tr>
</table>
</FooterTemplate>
</asp:DataList>
</asp:Panel>
<br />
<div id="div1" style="overflow: auto; height: auto; width: 97%;">
<asp:GridView ID="gv" runat="server" CssClass="tablecloth-theme" Width="97%" GridLines="Vertical"
AllowSorting="True" AllowPaging="True" PageSize="20" OnPageIndexChanging="gv_PageIndexChanging"
OnSorting="gv_Sorting" SelectedRowStyle-BackColor="Beige" OnSelectedIndexChanged="gv_SelectedIndexChanged">
<HeaderStyle BackColor="#7799AF" Font-Bold="True" Height="20px" Font-Names="Verdana"
Font-Size="7pt" ForeColor="White" HorizontalAlign="Left" />
<Columns>
<asp:CommandField SelectText="Details" ShowSelectButton="True" />
</Columns>
<AlternatingRowStyle BackColor="Gainsboro" />
<SelectedRowStyle BackColor="Beige" />
</asp:GridView>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Server code:
protected void Page_Load(object sender, EventArgs e)
{
try
{
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (!scriptManager.IsInAsyncPostBack)
{
DataInfo_Load();
}
//Page_Prepare();
}
catch (Exception ex)
{
ShowError(ex);
}
}
protected void DataInfo_Load()
{
try
{
DataSet_Load();
Filters_Load();
Grid_Load();
if ((int)ViewState["PageStatus"] >= 2)
{
if (ViewState["Saveable"] != null)
btnNew.Visible = (bool)ViewState["Saveable"];
else
btnNew.Visible = true;
}
else
btnNew.Visible = false;
}
catch (Exception ex)
{
throw ex;
}
}
protected void DataSet_Load()
{
try
{
Connection cn = new Connection();
DataSet ds = null;
string Query = hfSelStore.Value;
SqlCommand SQLcmd = new SqlCommand(Query);
SQLcmd.CommandType = System.Data.CommandType.StoredProcedure;
ds = cn.ExecuteSqlCmd(cn.SqlLocalConn, SQLcmd);
ViewState["DataSet"] = ds;
}
catch (Exception ex)
{
throw ex;
}
}
protected void Filters_Load()
{
try
{
if (ViewState["DataSet"] == null)
{
throw new Exception("No DataSet!");
}
DataSet ds = (DataSet)ViewState["DataSet"];
if (ds == null)
{
throw new Exception("DataSet is empty!");
}
if (ds.Tables.Count == 5)
{
//contains filter
pnlFilter.Visible = true;
DataView view = new DataView(ds.Tables[4]);
view.Sort = "lId";
dlFilter.DataSource = view;
dlFilter.DataBind();
}
}
catch (Exception ex)
{
throw ex;
}
}
protected void dlFilter_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
// Retrieve the Label control in the current DataListItem.
HiddenField hfFilterName = (HiddenField)e.Item.FindControl("hfFilterName");
HiddenField filtertype = (HiddenField)e.Item.FindControl("hfFilterType");
if (filtertype != null)
{
DataListItem dlt = ((filtertype.Parent) as DataListItem);
int itemIndex = dlt.ItemIndex;
Label lbl = new Label();
lbl.ID = "lbl";
lbl.Text = hfFilterName.Value;
lbl.Attributes.Add("style", "font-size:7pt; color:#005780; font-weight:bold;");
Control ctr = Control_Create(filtertype.Value);
ctr.ID = "val";
dlt.Controls.Add(new LiteralControl("<table><tr><td valign=\"middle\" style=\"width: 120px; text-align: right;\">"));
dlt.Controls.Add(lbl);
dlt.Controls.Add(new LiteralControl("</td><td>"));
dlt.Controls.Add(ctr);
dlt.Controls.Add(new LiteralControl("</td></tr></table>"));
}
}
}
catch (Exception ex)
{
ShowError(ex);
}
}
protected Control Control_Create(string controlType)
{
Control c = new TextBox();
try
{
if (controlType == "TextBox")
c = new TextBox();
else if (controlType == "CheckBox")
c = new CheckBox();
else if (controlType == "DropDownList")
c = new DropDownList();
else if (controlType == "RadioButton")
c = new RadioButton();
//else if (controlType == "Checkbox")
// c = new TextBox();
//else if (controlType == "Checkbox")
// c = new TextBox();
}
catch (Exception ex)
{
throw ex;
}
return c;
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
gv.SelectedIndex = -1;
gv.PageIndex = 0;
Grid_Load();
}
catch (Exception ex)
{
ShowError(ex);
}
}
Can you help me out?
Thanks in advance!
First of all you do not need to load the listview on each postback. The ListView is able to hold the state information during the PostBack. However you should not call the DataBind() function on each postback, if you do so, it will loose the state information. Check where are you binding the ListView
Regarding the dynamic controls added to the ListView, if you add them in the ItemDataBound event as you are doing right now, they retain the state during postback if you call the DataBind() function during first page load i.e under
if(!IsPostBack) code block.
Another point is avoid creating the controls with html in the codebehind as much as possible. You can add these controls in the ItemTemplate and access them in the code behind. If you want to create multiple controls like a table under the list view, you can add a repeater control in the listview's ItemTemplate and bind the repeater in OnItemDataBound event of the ListView.
As I dont see your complete code like Control_Create function, I cannot assist or show code on how you can use Repeater control inside the ListView.
I have a page SendResults.aspx that holds a button and a ListView with ItemTemplate set to a user control (3 labels and 2 textboxes) that gets it's data from a matching object.
On Page_Load I fill the List with data (this works well).
When the button is clicked I want to take the user input in the user-control's textboxes and do something with it.
However I always get the initial value and not the updated one.
Here is the code:
The user-control "MatchControl.ascx"
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="MatchControl.ascx.cs" Inherits="TotoMondeal.Controls.MatchControl" %>
<div>
<asp:Image ID="Team1FlagImage" runat="server" />
<asp:Label ID="Team1Label" runat="server" Width="150px"></asp:Label>
<asp:TextBox ID="Team1TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px" AutoPostBack="true" OnTextChanged="Team1TextBox_TextChanged"></asp:TextBox>
<asp:Label ID="Colon" runat="server" Font-Size="XX-Large" Text=":"></asp:Label>
<asp:TextBox ID="Team2TextBox" runat="server" MaxLength="2" TextMode="Number" Width="50px"></asp:TextBox>
<asp:Label ID="Team2Label" runat="server" Width="150px"></asp:Label>
<asp:Image ID="Team2FlagImage" runat="server" />
</div>
The user-control code-behind:
public partial class MatchControl : System.Web.UI.UserControl
{
public Match Match
{
get
{
object obj = ViewState["Match"];
return (obj == null) ? new Match() : (Match)obj;
}
set
{
ViewState["Match"] = value;
}
}
public string Team1Score
{
get { return Team1TextBox.Text; }
set { Team1TextBox.Text = value; }
}
public string Team2Score
{
get { return Team2TextBox.Text; }
set { Team2TextBox.Text = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
Team1Label.Text = Match.Team1Name;
Team2Label.Text = Match.Team2Name;
Team1TextBox.Text = Match.Team1Score.ToString();
Team2TextBox.Text = Match.Team2Score.ToString();
Team1TextBox.Enabled = Match.EnableTextBox;
Team2TextBox.Enabled = Match.EnableTextBox;
Team1FlagImage.ImageUrl = #"~/FlagImages/" +Match.Team1Name + ".png";
Team2FlagImage.ImageUrl = #"~/FlagImages/" + Match.Team2Name + ".png";
}
protected void Team1TextBox_TextChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if (textBox != null)
{
try
{
Match updatedMatch = new Match()
{
MatchId = Match.MatchId,
MatchDate = Match.MatchDate,
Result = Match.Result,
Team1Name = Match.Team1Name,
Team1Score = Convert.ToInt32(textBox.Text),
Team2Name = Match.Team2Name,
Team2Score = Match.Team2Score,
EnableTextBox = Match.EnableTextBox
};
Match = updatedMatch;
}
catch (Exception ex)
{
throw ex;
}
}
}
The SendResults.aspx:
<%# Page Title="שלח תוצאות" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="SendResults.aspx.cs" Inherits="TotoMondeal.SendResults" %>
<%# Register TagPrefix="TOTO" TagName="MatchControl" Src="~/Controls/MatchControl.ascx" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<h2><%: Title %>.</h2>
<div class="jumbotron">
<asp:ListView ID="TodayMatchesList" runat="server">
<ItemTemplate>
<TOTO:MatchControl ID="MatchControl" Match="<%# Container.DataItem %>" runat="server" />
</ItemTemplate>
</asp:ListView>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</asp:Content>
the SendResults code-behind:
public partial class SendResults : Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
foreach (Match match in matches)
{
match.EnableTextBox = true;
}
this.TodayMatchesList.DataSource = matches;
this.TodayMatchesList.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < TodayMatchesList.Items.Count; i++)
{
MatchControl match = (MatchControl)TodayMatchesList.Items[i].FindControl("MatchControl");
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
}
}
}
The problem is that in this line:
TextBox textBox = (TextBox)match.FindControl("Team1TextBox");
string txt = textBox.Text;
I always get the initial value from the database, and not the user updated input.
Please help I'm new at this.
Your List is getting overwritten every time you post back. Add this in Page_Load for SendResults
if ( !Page.IsPostBack )
{
List<Match> matches = new List<Match>();
matches = Queries.GetTodayMatches(DateTime.Now);
...etc...
}
In addition to checking IsPostBack you need to handle saving your control properties in the ViewState. As suggested here: User control (ascx) and properties
Example from post:
public string Title {
get { return Convert.ToString(ViewState["Title"]); }
set { ViewState["Title"] = value; }
}
You would do this in your control class.
I have a problem that the value of listbox don't add into the database.
i have a checkboxlist and listbox, first i want to add all selected checkbox value in listbox, it works successfuly, and then i want to add that data of listbox come form checkboxlist to database on button click event, it do not work so how to solve this.
<div id="contentwrapper" class="contentwrapper">
<div id="validation" class="subcontent">
<form class="stdform stdform2" style="border-top:solid 1px #ddd">
<p>
<label>Hotel Name</label>
<span class="field">
<asp:DropDownList ID="ddlHotel" runat="server">
</asp:DropDownList>
</span>
</p>
<p>
<fieldset class="fieldset">
<legend class="legend">Facilities</legend>
<div>
<asp:CheckBoxList ID="cblFacility" runat="server" DataTextField="FacilityName" DataValueField="FacilityID" TextAlign="Right" RepeatColumns="5">
</asp:CheckBoxList>
<div class="clear">
</div>
</div>
</fieldset>
</p>
<p class="stdformbutton">
<asp:Button ID="btnAdd" runat="server" CssClass="radius2" Text="Add" onclick="btnAdd_Click" />
</p>
</form>
</div><!--subcontent-->
</div><!--contentwrapper-->
<div id="Div1" class="contentwrapper">
<div id="Div2" class="subcontent">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<form class="stdform stdform" style="border-top:solid 1px #ddd">
<p>
<span class="field">
<asp:ListBox ID="lstFacility" runat="server" SelectionMode="Multiple"></asp:ListBox><br />
</span>
</p>
<p class="stdformbutton">
<asp:Button ID="btnSubmit" runat="server" CssClass="submit radius2" Text="Submit" onclick="btnSubmit_Click" />
</p>
</form>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
</div><!--subcontent-->
</div>
AND .cs file is :
protected void Page_Load(object sender, EventArgs e)
{
string myConnectionString = "my connection string";
if (Session["admin"] != null)
{
lblEmail.Text = Session["adminEmail"].ToString();
lblAdmin.Text = "Wel Come " + Session["admin"].ToString();
lblAdmin1.Text = "Wel Come " + Session["admin"].ToString();
}
else
{
Response.Redirect("Login.aspx");
}
if (!Page.IsPostBack)
{
if (Session["hotelID"] != null)
{
ddlHotel.SelectedValue = Session["hotelID"].ToString();
}
ddlHotel.DataSource = dalMST_Hotel.SelectAll(myConnectionString);
ddlHotel.DataTextField = "HotelName";
ddlHotel.DataValueField = "HotelID";
ddlHotel.DataBind();
ddlHotel.Items.Insert(0, "Select Hotel");
BindData();
}
}
private void BindData()
{
string myConnectionString = "my connection string";
cblFacility.DataSource = dalMST_Facility.SelectAll(myConnectionString);
cblFacility.DataBind();
}
protected void btnAdd_Click(object sender, EventArgs e)
{
string s1 = string.Empty;
lstFacility.Items.Clear();
foreach (ListItem item in this.cblFacility.Items)
{
if (item.Selected)
{
lstFacility.Items.Add(item);
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string myConnectionString = "my connection string";
Page.Validate();
if (Page.IsValid)
{
DataTable dt = dalMST_FacilityTran.SelectAll(myConnectionString);
int cnt = dt.Rows.Count;
entMST_FacilityTran.HotelID = Convert.ToInt32(ddlHotel.SelectedValue);
entMST_FacilityTran.FacilityID = 0;
entMST_FacilityTran.Created = DateTime.Now;
entMST_FacilityTran.Modified = DateTime.Now;
#region Insert,Update
for (int i = 0; i < lstFacility.Items.Count; i++)
{
int flag = 0;
for (int j = 0; j < cnt; j++)
{
int hotelid = Convert.ToInt32(dt.Rows[j][2].ToString());
int facilityid = Convert.ToInt32(dt.Rows[j][1].ToString());
if (lstFacility.Items[i].Selected)
{
entMST_FacilityTran.FacilityID = Convert.ToInt32(lstFacility.Items[i].Value);
if (entMST_FacilityTran.HotelID == hotelid && entMST_FacilityTran.FacilityID == facilityid)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
}
if (flag == 0)
{
if (dalMST_FacilityTran.Insert(entMST_FacilityTran, myConnectionString))
{
//txtFacility.Text = "";
//Response.Redirect("AddFacility.aspx");
//return;
}
}
}
Response.Redirect("AddRoomCategory.aspx");
#endregion
}
}
There is problem related to update panel.
Use below code:
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:PostBackTrigger ControlID="btnSubmit" />
</Triggers>
So submit button cilck event will fire.
Thanks
First You have to remove Nested For Loop
String lstName;
for (int i= 0; i< listBoxEmployeeName.Items.Count;i++)
{
lstName=listBoxEmployeeName.Items[i].Text;//Here your value stored in lstName
//here continue you insert query
}
I have a Repeater control, that I have now reduced to just changing text in a text box when clicking the associated button.
However, this is not happening.
Here is my code so far:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
<asp:Repeater ID="rptPdfList" runat="server" OnItemCommand="rptPdfList_ItemCommand">
<HeaderTemplate>
<table>
<tr>
<td>File Name</td>
<td></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblName" runat="server" Text=<%#Eval("FileName") %>></asp:Label>
</td>
<td>
<asp:Button ID="btnLoad" runat="server" Text="Load" CommandName="LoadDoc"/>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
<br />
<asp:Button ID="btnLoad" runat="server" Text="Load" OnClick="btnLoad_Click" /><br />
<iframe runat="server" id="pdfHolder"></iframe>
<br />
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
Code Behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
private void GetFiles()
{
rptPdfList.DataSource = Pdf();
rptPdfList.DataBind();
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}
public static List<PdfList> Pdf()
{
string pdfDir = HostingEnvironment.MapPath("~") + #"PDF\";
DirectoryInfo directory = new DirectoryInfo(pdfDir);
FileInfo[] pdfFiles = directory.GetFiles("*.pdf", SearchOption.AllDirectories);
List<PdfList> pdfLists = pdfFiles.Select(pdfFile => new PdfList
{
FileName = pdfFile.Name
}).ToList();
return pdfLists;
}
}
public class PdfList
{
public string FileName { get; set; }
}
Ca anyone see where I went wrong?
Edit, added all the code
Change this:
protected void Page_Load(object sender, EventArgs e)
{
GetFiles();
}
to this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GetFiles();
}
You are calling the GetFiles() each time so it is always returning to the initial state.
I am binding your repeater like this and it works fine for me, Just place your binding function in
if (!Page.IsPostBack)
condition :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (DataClassesDataContext dc = new DataClassesDataContext())
{
var v = (from s in dc.t_employees select s).ToList();
rptPdfList.DataSource = v;
rptPdfList.DataBind();
}
}
}
protected void rptPdfList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
Label lblName = (Label)e.Item.FindControl("lblName");
switch (e.CommandName)
{
case "LoadDoc":
//xpdfHolder.Attributes.Add("src", "PDF/" + lblName.Text);
lblTest.Text = "test";
lblName.Text = "oops";
break;
}
}