add values from listbox to database - c#

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
}

Related

Prevent page auto Reloading using asp.net C#

I have a website and when opening the page, reloading automatically infinite times.
How do I stop the page from reloading automatically infinite times?
This code is doing that reloading , when i commented this code the reloading not reload the page.
but i don't know how fix it .
any advise .
This is the html code
<h1>
Edit Project</h1>
<div id="Div3" class="entryRow">
<div class="title">
<asp:Label ID="Label8" runat="server" Text="Select Developer"></asp:Label>
</div>
<div class="entry">
<asp:DropDownList ID="ddldeveloperForEdit" runat="server" AppendDataBoundItems="true"
DataSourceID="EntityDataSource2" DataTextField="DeveloperName" DataValueField="DeveloperPK">
<asp:ListItem Text="Select Developer" Value="0"></asp:ListItem>
</asp:DropDownList>
<asp:EntityDataSource ID="EntityDataSource2" runat="server" ConnectionString="name=MyCBEntities"
DefaultContainerName="MyCBEntities" EntitySetName="Developer" Select="it.[DeveloperPK], it.[DeveloperName]"
OrderBy="it.[DeveloperName]">
</asp:EntityDataSource>
Select Project
<asp:DropDownList ID="ddlProjects" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="ddlProjects_SelectedIndexChanged">
</asp:DropDownList>
//here this control <cc1:CascadingDropDown code when i comment it the reloading not happened, here the issue how fix it
<cc1:CascadingDropDown ID="CascProjects" PromptText="Select Project" PromptValue="0" Enabled="true"
ServiceMethod="GetProjectsListByDeveloper" ServicePath="~/WebServ/MyCBWebService.asmx"
Category="selProject" TargetControlID="ddlProjects" runat="server" ParentControlID="ddldeveloperForEdit">
</cc1:CascadingDropDown>
</div>
<div class="msg">
</div>
</div>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateDevelopers();
}
else
{
return;
}
}
private void PopulateDevelopers()
{
using (var db = new MyCBEntities())
{
if (ddlDevelopers.Items.Count > 0)
{
ddlDevelopers.ClearSelection();
ddlDevelopers.Items.Clear();
}
var developers = db.Developer.OrderBy(z => z.DeveloperName).ToList();
ddlDevelopers.Items.Add(new ListItem("Select Developer", "0-1"));
foreach (var developer in developers)
{
ddlDevelopers.Items.Add(new ListItem(developer.DeveloperName, developer.DeveloperPK.ToString()));
}
ddlDevelopers.SelectedIndex = 0;
}
}
This is the ServiceMethod="GetProjectsListByDeveloper"
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod]
public CascadingDropDownNameValue[] GetProjectsListByDeveloper(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
MyCBEntities db = new MyCBEntities();
string developerIdStr = "";
if (kv.Count > 0 && kv.ContainsKey("country"))
{
developerIdStr = kv["country"];
}
else if (kv.Count > 0 && kv.ContainsKey("undefined"))
{
developerIdStr = kv["undefined"];
}
int developerId;
int.TryParse(developerIdStr, out developerId);
List<CascadingDropDownNameValue> values =
new List<CascadingDropDownNameValue>();
if (developerId > 0)
{
var projectList = db.DevelopersProject.Where(z => z.DeveloperFK == developerId).ToList();
foreach (var project in projectList)
{
values.Add(new CascadingDropDownNameValue(project.ProjectName, project.DeveloperProjectPK.ToString()));
}
}
return values.ToArray();
}

Asp.net how to maintain radio button selection when using datapager

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

How to get value from dynamically created radiobuttonlist using listview?

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>

Button in asp.net web forms dont fire event

can you help me with something i struggle for 4 days, button event doesn't fire :( In the MasterPage i use this to add control
<Login:UserLogin runat="server" ID="UserLogin" EnableViewState="false" > </Login:UserLogin>
and the control is this
<%# Control Language="C#" AutoEventWireup="true" CodeFile="UserLogin.ascx.cs" Inherits="BookApartmentsPortal.controls.UserLogin" %>
<%# Register TagPrefix="MultiLanguage" Namespace="MultiLanguage.multilanguage" %>
<%--
<script type="text/javascript">
function DeleteKartItems() {
var inputEmail = $("#ctl00_UserLogin_txtEmailVal").val();
var user = {
email: "s.krastanov",
password: "1"
};
$.ajax({
type: "POST",
url: 'PublicDefault.aspx/Getvalues',
data: JSON.stringify({ person: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
$("#ctl00_PublicDefault_buttonLog").Click();
}
</script>--%>
<h3>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral13" runat="server" Resource="669" />
</h3>
<form action="/" method="POST" id="formasd">
<div class="">
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral14" runat="server" Resource="858" />
<%--user name input field--%>
<input type="text" class="modal-input" runat="server" size="20" id="txtEmailVal"
name="txtEmail" />
<%-- <asp:TextBox runat="server" CssClass="modal-input" ID="txtEmailVal" ></asp:TextBox> --%>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral21" runat="server" Resource="205" />
<%--password input field--%>
<%--<input type="password" class="modal-input" runat="server" size="1" maxlength="20" id="txtPassword" />--%>
<asp:TextBox runat="server" CssClass="modal-input" TextMode="Password" ID="txtPassword"
MaxLength="20" CausesValidation="false"></asp:TextBox>
<asp:Label ID="Label1" runat="server">
</asp:Label>
<asp:Panel ID="panelLogin" runat="server" DefaultButton="btnLogon">
<asp:Button runat="server" ID="btnLogon" Text="Click" CssClass="login-btn" OnClick="btnLogon_Click"></asp:Button>
</asp:Panel>
<%-- <button class="login-btn" runat="server" id="btnLogon" name="btnLogon" onclick="DeleteKartItems()">
<i class="fa fa-paper-plane"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
</button>--%>
<div id="divResult">
</div>
</div>
</form>
<asp:HyperLink ID="LoginFB" Target="_blank" runat="server" CssClass="btn btn-block btn-social btn-facebook fb-login">
<i class="fa fa-facebook"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral27" runat="server" Resource="1306" /></asp:HyperLink>
<a href="#lost-pass" class="button-modal various-login"><i class="fa fa-lock"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral22" runat="server" Resource="164" /></a>
<a href="#reg" class="button-modal reg"><i class="fa fa-user"></i>
<MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral23" runat="server" Resource="1271" /></a>
Backend is this:
public partial class UserLogin : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
Response.Write("you click");
}
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
LoginFB.NavigateUrl = "https://www.facebook.com/v2.0/dialog/oauth/?client_id=" + ConfigurationManager.AppSettings["FacebookAppId"] + "&redirect_uri=http://" + ConfigurationManager.AppSettings["URL"].ToString() + "/Publish/UserFB.aspx&response_type=code&state=1";
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
//btnLogon.ServerClick += new EventHandler(btnLogon_Click);
this.btnLogon.Click += new System.EventHandler(btnLogon_Click);
//btnLogon.ServerClick += new CommandEventHandler(btnLogonClick);
// btnLogon.Command += btnLogon_Click;
}
public void btnLogon_Click(object sender, EventArgs e)
{
Label1.Text = "submit button is press";
// if (LoginSet == false )
// {
string Name = txtPassword.Text;
string Dev = txtEmailVal.Value;
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal.Value.Trim(), txtPassword.Text.Trim(), true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Response.Cookies[FormsAuthentication.FormsCookieName].Expires = DateTime.Now;
FormsAuthentication.RedirectFromLoginPage(txtEmailVal.Value.Trim(), false);
Session["LoginUserName"] = txtEmailVal.Value.Trim();
// _loginSet = true;
}
else
{
// _loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
// _loginSet = false;
}
//}
}
}
This control is for login form and i just cant get the values from input boxes because event don't trigger. One idea was to make AJAX post to static method but after that i cant make new session with this variables.
I try everything and this button just doesn't fire the event. I don't know what to do next, can you help me.
Ok after one more day of struggle, i manage to make a little walk around path:
In the first step i made a Button to fire event (javascript function) and make cookie, after that i make click event for actual asp:Button :
<script type="text/javascript">
function LoginClicked() {
var inputEmail = $("#txtEmail").val();
var inputPass = $("#txtPassword").val();
if(inputEmail != "" && inputPass != ""){
var userSet = inputEmail + "&" + inputPass;
setCookie("UserSettings", userSet, 1);
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*1*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
$("#ctl00_UserLogin_btnLogon").click();
}
}
</script>
And here is the buttons:
<asp:Panel runat="server" ID="panekl">
<asp:Button runat="server" ID="btnLogon" UseSubmitBehavior="false" CssClass="no-display" ></asp:Button>
</asp:Panel>
<button class="login-btn" id="btnLogon1" name="btnLogon1" onclick="LoginClicked()">
<i class="fa fa-paper-plane"></i><MultiLanguage:MultiLanguageLiteral ID="MultiLanguageLiteral4" runat="server" Resource="1270" />
And in the back end, i get the cookie, split it, and check for validation:
public void btnLogon_Click()
{
if (LoginSet == false )
{
string[] txtSome = Request.Cookies["UserSettings"].Value.Split('&');
if (Request.Cookies["UserSettings"] != null && txtEmailVal != "" && txtPassword != "")
{
txtEmailVal = txtSome[0].Trim();
txtPassword = txtSome[1].Trim();
}
String[] RemoteAddr = Request.ServerVariables.GetValues("REMOTE_ADDR");
if (RemoteAddr.Length <= 0)
return;
LoginDB oLoginDb = new LoginDB(txtEmailVal, txtPassword, true, RemoteAddr[0].ToString());
oLoginDb.Database = new SQLDatabase(Convert.ToString(ConfigurationManager.ConnectionStrings["dbConnectionString"].ToString()));
try
{
if (oLoginDb.Authenticate(ConfigurationManager.AppSettings["SecKeyIni"].ToString(), ConfigurationManager.AppSettings["SecKeySec"].ToString()))
{
Session["IdUserLogin"] = txtEmailVal;
_loginSet = true;
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
Label1.Text = "submit button is press";
}
else
{
_loginSet = false;
}
}
catch (Exception Exception)
{
Context.Trace.Warn(Exception.Message);
Global.ErrorMessage(Exception.Message, Context);
_loginSet = false;
}
}
}
This was the only way i figured out to get values from the control.

How to get value from dropdownlist in repeater

In Below code I used repeater control and i want to get value from dropdownlist on linkbutton click that is inside the repeater. In below code when i click on button then dropdownlist is return first value.
Please reply as soon as possible Thanks in advance.
ASP.NET MARKUP
<asp:Repeater ID="rptProduct" runat="server" OnItemCommand="rptProduct_ItemDataBound">
<ItemTemplate>
<div class="span6">
<h3><%# Eval("ProductName")%>
</h3>
<hr class="soft" />
<form class="form-horizontal qtyFrm">
<div class="control-group">
<label class="control-label">
<span>Select Quantity</span>
</label>
<div class="controls">
<asp:DropDownList ID="ddlQuantity" class="span1" runat="server">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="lnkAddCart" runat="server" class="btn btn-large btn-primary pull-right" CommandName="Add">Add to cart
<i class=" icon-shopping-cart"></i>
</asp:LinkButton>
</div>
</div>
<asp:Label ID="lblError" Visible="false" class="alert alert-block alert-error" runat="server" Text=""></asp:Label>
</form>
<hr class="soft clr" />
<p><%#Eval("Description")%>
</p>
<a class="btn btn-small pull-right" href="#detail">More Details</a>
<br class="clr" />
<hr class="soft" />
</div>
</ItemTemplate>
</asp:Repeater>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptCategory.DataSource = bll.getCategory();
rptCategory.DataBind();
if (Request.QueryString["productID"] != null)
{
BindDataList();
bindcartdetail();
}
}
}
protected void rptProduct_ItemDataBound(object sender, RepeaterCommandEventArgs e)
{
DropDownList ddlQuantity = (DropDownList)e.Item.FindControl("ddlQuantity");
Label lblError = ((Label)e.Item.FindControl("lblError"));
Image photo = (Image)e.Item.FindControl("imgProduct");
if (e.CommandName == "Add")
{
string qty = ddlQuantity.SelectedValue;
Session["proQty"] = qty;
Session["photo"] = photo.ImageUrl;
cart();
}
}
protected void cart()
{
int productID = Convert.ToInt32(Request.QueryString["productID"]);
DataTable dtproduct = new DataTable();
dtproduct = bll.getProductbyID(productID);
string proCode = dtproduct.Rows[0][3].ToString();
string proName = dtproduct.Rows[0][4].ToString();
int quantity = Convert.ToInt32(Session["proQty"]);
string photo = Session["photo"].ToString();
// SESSION ID
SessionIDManager manager = new SessionIDManager();
string OldID = Context.Session.SessionID;
if (OldID == "")
{
string sessionid = manager.CreateSessionID(Context);
bool redirected = false;
bool isAdded = false;
manager.SaveSessionID(Context, sessionid, out redirected, out isAdded);
Session["sessionid"] = sessionid;
Session["proid"] = productID;
Session["proCode"] = proCode;
Session["proname"] = proName;
DataTable dtinfo = new DataTable();
dtinfo = bll.getCartInfo(proCode, sessionid);
// PRODUVT IS AVLB OR NOT
if (dtinfo.Rows.Count > 0)
{
int proquantity = Convert.ToInt32(dtinfo.Rows[0][3].ToString());
proquantity = proquantity + quantity;
bll.updateCart(proquantity, proCode, sessionid);
Response.Redirect("Product.aspx");
}
else
{
bll.addCart(proCode, proName, quantity, sessionid, photo);
Response.Redirect("Product.aspx");
}
}
else
{
string sessionid = OldID;
Session["sessionid"] = sessionid;
Session["proid"] = productID;
Session["proCode"] = proCode;
Session["proname"] = proName;
DataTable dtinfo = new DataTable();
dtinfo = bll.getCartInfo(proCode, sessionid);
if (dtinfo.Rows.Count > 0)
{
int proquantity = Convert.ToInt32(dtinfo.Rows[0][3].ToString());
proquantity = proquantity + quantity;
bll.updateCart(proquantity, proCode, sessionid);
Response.Redirect("Product.aspx");
}
else
{
bll.addCart(proCode, proName, quantity, sessionid, photo);
Response.Redirect("Product.aspx");
}
}
}
<div class="controls">
<asp:DropDownList ID="ddlQuantity" class="span1" runat="server">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="5">5</asp:ListItem>
</asp:DropDownList>
<asp:LinkButton ID="lnkAddCart" runat="server" class="btn btn-large btn-primary pull-right" OnClick="lnkAddCart_click">Add to cart <i class=" icon-shopping-cart"></i> </asp:LinkButton>
</div>

Categories