Button in asp.net web forms dont fire event - c#

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.

Related

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

Controls from placeholder cannot be accessed

I have generated an ASP.NET C# website with the visual studio 2013 wizard in order to get the authentication code and add it to my web app.
I have copied all files and everything looks fine except one thing...
the RegisterExternalLogin.cs file gives me an error in my web, but in the generated sample it works and I don't know why.
This is the error:
RegisterExternalLogin.aspx.cs(65,17,65,25): error CS0103: The name 'userName' does not exist in the current context
RegisterExternalLogin.aspx.cs(82,55,82,63): error CS0103: The name 'userName' does not exist in the current context
Here is the RegisterExternalLogin.aspx
<%# Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="RegisterExternalLogin.aspx.cs" Inherits="Account_RegisterExternalLogin" Async="true" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h3>Register with your <%: ProviderName %> account</h3>
<asp:PlaceHolder runat="server">
<div class="form-horizontal">
<h4>Association Form</h4>
<hr />
<asp:ValidationSummary runat="server" ShowModelStateErrors="true" CssClass="text-danger" />
<p class="text-info">
You've authenticated with <strong><%: ProviderName %></strong>. Please enter a user name below for the current site
and click the Log in button.
</p>
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="userName" CssClass="col-md-2 control-label">User name</asp:Label>
<div class="col-md-10">
<asp:TextBox runat="server" ID="userName" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="userName"
Display="Dynamic" CssClass="text-danger" ErrorMessage="User name is required" />
<asp:ModelErrorMessage runat="server" ModelStateKey="UserName" CssClass="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<asp:Button runat="server" Text="Log in" CssClass="btn btn-default" OnClick="LogIn_Click" />
</div>
</div>
</div>
</asp:PlaceHolder>
</asp:Content>
and RegisterExternalLogin.aspx.cs
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using System;
using System.Web;
using QuoteHD;
public partial class Account_RegisterExternalLogin : System.Web.UI.Page
{
protected string ProviderName
{
get { return (string)ViewState["ProviderName"] ?? String.Empty; }
private set { ViewState["ProviderName"] = value; }
}
protected string ProviderAccountKey
{
get { return (string)ViewState["ProviderAccountKey"] ?? String.Empty; }
private set { ViewState["ProviderAccountKey"] = value; }
}
protected void Page_Load()
{
// Process the result from an auth provider in the request
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
Response.Redirect("~/Account/Login");
}
if (!IsPostBack)
{
var manager = new UserManager();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
Response.Redirect("~/Account/Login");
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
// Apply Xsrf check when linking
var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
Response.Redirect("~/Account/Login");
}
var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
userName.Text = loginInfo.DefaultUserName;
}
}
}
protected void LogIn_Click(object sender, EventArgs e)
{
CreateAndLoginUser();
}
private void CreateAndLoginUser()
{
if (!IsValid)
{
return;
}
var manager = new UserManager();
var user = new ApplicationUser() { UserName = userName.Text };
IdentityResult result = manager.Create(user);
if (result.Succeeded)
{
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
Response.Redirect("~/Account/Login");
return;
}
result = manager.AddLogin(user.Id, loginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
return;
}
}
AddErrors(result);
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
I solved the problem...
I had to wrap the entire codebehind in a namespace
QuoteHD.Account
{
}

Asyncupload control of AjaxControlToolkit

I am using asyncupload control of AjaxControlToolkit and I want to check the file to be uploding is already exists or
not on server.
How we can do this?
Please help me out.
<!-- Client side code for control-->
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
<!-- Control Code in aspx-->
<tr>
<td></td>
<td>
<cc1:AsyncFileUpload ID="FileUpload2" Width="265px" runat="server"
OnClientUploadError="uploadError"
OnClientUploadStarted="StartUpload"
OnClientUploadComplete="UploadComplete"
CompleteBackColor="Lime" UploaderStyle="Modern"
ErrorBackColor="Red"
ThrobberID="Throbber"
onuploadedcomplete="AsyncFileUpload1_UploadedComplete"
UploadingBackColor="#66CCFF" />
<asp:Label ID="Throbber" runat="server" Style="display: none">
<img src="../../images/indicator.gif" align="absmiddle" alt="loading" />
</asp:Label>
<asp:HiddenField ID="hdnField" runat="server" value=""/>
</td>
</tr>
//.CS Code for ayncupload control
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath="C:\Documents\temp.txt"
if(File.Exists(filePath))
{
hdnField.value="1";//Not able to access this value
}
}
Thanks!!
you just need to set your hidden field value at client side script.
See I have made little changes in your server side code:
protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
{
string filePath = "C:\\Documents\\temp.txt";
string hiddenValue = "0";
if (File.Exists(filePath))
{
hiddenValue = "1";
}
//This script will set required value for hidden field.
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "SetHiddenField", String.Format("top.$get('{0}').value = '{1}'", hdnField.ClientID, hiddenValue), true);
}
Make changes in your script location as follow:
<ajaxToolkit:ToolkitScriptManager runat="Server" EnablePartialRendering="true" ID="ScriptManager1" />
<script>
function uploadError(sender, args) {
//document.getElementById('lblStatus').innerText = args.get_fileName(), "<span style='color:red;'>" + args.get_errorMessage() + "</span>";
}
function StartUpload(sender, args) {
var nodeSelectedText = document.getElementById('<%=lblFileLocation1.ClientID%>').innerHTML;
if (nodeSelectedText == "") {
$("#msgMissingSelection").dialog("open");
args.set_cancel(true);
}
else {
return true;
}
}
function UploadComplete(sender, args) {
var hdnFieldVal = document.getElementById('<%=hdnField.ClientID%>');
if(hdnFieldVal.value == "1")
{
$("#msgFileUploadExists").dialog("open");
}
else
{
$("#msgFileUpload").dialog("open");
}
}
</script>
Check if the file exists using the following:-
File.Exists
You can compare based on the filename.

add values from listbox to database

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
}

JavaScript Validation to TextBox in a GridView in ASP.Net

I have a GridView in Which I have four TextBoxes in the Template Field. I have one Button below the GridView.
How to validate the TextBoxes in the GridView, When the Button Clicked?
use RequiredFieldValidator and set ValidationGroup="gridview", check below example
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfv" runat="server" ControlToValidate="TextBox3" ValidationGroup="gridview" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="Button" ValidationGroup="gridview" CausesValidation="true" />
</ItemTemplate>
</asp:TemplateField>
You can use the JQuery Validation Plugin
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate /lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});;
</script>
<script>
$(document).ready(function(){
$("#myform").validate({
rules: {
field: "required"
}
});
});
<body>
<form id="myform">
<label for="field">Required: </label>
<input class="left" id="field" name="field" />
<br/>
<input type="submit" value="Validate!" />
</form>
</body>
<script type="text/javascript">
function ValidateGridview() {
titlename = document.getElementById('<%=((TextBox)grd_party_influenc.FooterRow.FindControl("txt_f_title")).ClientID%>');
if (titlename.value ==0) {
alert("Please Insert The Title ....");
titlename.focus();
return false;
}
// return true;
}
</script>
And then call the JavaScript function through link button like this:
<asp:LinkButton ID="lnk_btn_insert" runat="server" CommandName="Insert" OnClientClick="ValidateGridview()">Insert</asp:LinkButton>
i have 7 textbox
ok i have worked on my JS function and it worked for me.hope it will
work for everyone else.in my code i have taken a variable
success which is working as a flag and i am checking it twice and
returning true at the end so that if one of the textbox is not empty
and other not it will not return true.
sorry for poor editing
function fnCheck(val) {
var success = true;
var v = val.id.split('_')[1];
var merter = document.getElementById('GridSubMeter_' + v + '_txtMeterIdn').value.trim();
var Billper = document.getElementById('GridSubMeter_' + v + '_txBillPer').value.trim()
var Endkwh = document.getElementById('GridSubMeter_' + v + '_txEndKwh').value.trim();
var startkwh = document.getElementById('GridSubMeter_' + v + '_txStartKwh').value.trim();
var ReadEndDate = document.getElementById('GridSubMeter_' + v + '_txReadEndDate').value.trim();
var ReadStartDate = document.getElementById('GridSubMeter_' + v + '_txReadStartDate').value.trim();
var CTFACT = document.getElementById('GridSubMeter_' + v + '_txCTFact').value.trim();
debugger;
if (merter != '') {
}
else {
alert("Meter Identifier is Required Field");
success = false;
}
if (Billper != '') {
}
else {
alert("Bill Period is Required Field");
success = false;
}
if (Endkwh != '') {
}
else {
alert("EndKwh is Required Field");
success = false;
}
if (startkwh != '') {
}
else {
alert("StartKwh is Required Field");
success = false;
}
if (ReadEndDate != '') {
}
else {
alert("Read EndDate is Required Field");
success = false;
}
if (ReadStartDate != '') {
}
else {
alert("Read StartDate is Required Field");
success = false;
}
if (CTFACT != '') {
}
else
{ alert("CT Factor is Required Field");
success = false;
}
return success;
}
onclientclick
<asp:Button ID="btn_Update" Style="background-color: #B2DE94; width: 40px" CausesValidation="false" runat="server" OnClientClick="return fnCheck(this);" Text="Update" CommandName="Update" />

Categories