JavaScript Validation to TextBox in a GridView in ASP.Net - c#

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" />

Related

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.

Dynamic grid on ASP.NET

I here to seek an advice ,what is the best approach.
here is the scenario.
I am building my project ASP.NET (C#)
I need to add an dynamic drop down box based on that two other text box related to drop down.
for example :
I have a button called "ADD LANDSCAPE", every time this triggered, i have to create an dynamic drop down "ddlLandscap" and two text boxes so the user can enter landscape value for each text box.
Can you guys please advise what's the best approach
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CS1.aspx.cs" Inherits="workout.CS1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="../jquery/jquery-ui.css" rel="stylesheet" />
<script src="../jquery/jquery-1.12.0.js"></script>
<script src="../jquery/jquery-ui.js"></script>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
.table {
border: 1px solid #ccc;
border-collapse: collapse;
}
.table th {
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
.table th, .table td {
padding: 5px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="gvCustomers1" CssClass="table" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Slno" ItemStyle-Width="50px" ItemStyle-CssClass="Slno">
<ItemTemplate>
<%# Eval("Slno") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" ItemStyle-Width="150px" ItemStyle-CssClass="Name">
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150px" ItemStyle-CssClass="Country">
<ItemTemplate>
<%# Eval("Country")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Option">
<ItemTemplate>
<asp:Button ID="lnkDelete" runat="server" Text="Delete" OnClientClick="Confirmationbox(this);" />
<asp:Button ID="btn_update" runat="server" Text="Update" OnClientClick="updateable(this);" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnNewUser" runat="server" Text="Add" OnClientClick="return false;" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" OnClientClick="formatData()" />
<br />
<div id="dialog-form" title="Create new user">
<p class="validateTips">All form fields are required.</p>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">Name:<br />
<asp:TextBox ID="txtName" runat="server" Width="140" Text="" />
</td>
<td style="width: 150px">Country:<br />
<asp:TextBox ID="txtCountry" runat="server" Width="140" Text="" />
</td>
</tr>
</table>
</div>
<div id="dialog-form-edit" title="Edit user">
<p class="validateTips">All form fields are required.</p>
<asp:HiddenField ID="hdslno" runat="server" Value="" />
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">Name:<br />
<asp:TextBox ID="TextBox1" runat="server" Width="140" Text="" />
</td>
<td style="width: 150px">Country:<br />
<asp:TextBox ID="TextBox2" runat="server" Width="140" Text="" />
</td>
</tr>
</table>
</div>
<br />
<script type="text/javascript">
var dialog,editDialog;
function formatData() {
var formatdata = "";
$( '#gvCustomers1 tr:gt(0)' ).each( function () {
$( this ).find( 'td' ).each( function () {
if ( $( this ).hasClass( "Slno" ) || $( this ).hasClass( "Name" ) || $( this ).hasClass( "Country" ) ) {
formatdata += $( this ).html() + "|";
}
} );
formatdata += ",";
} );
alert( formatdata );
return false;
}
$(function () {
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": AddRow,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
$("#txtName").val("");
},
open: function () {
var nr = $('#dialog-form').data('param');
if (nr) {
$("#txtName").val(nr);
} else {
$("#txtName").val("");
}
}
});
editDialog = $("#dialog-form-edit").dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Create an account": UpdateRow,
Cancel: function () {
editDialog.dialog("close");
}
},
close: function () {
$("#txtName").val("");
},
open: function () {
var nr = $('#dialog-form-edit').data('param');
console.log(nr);
$( "#hdslno" ).val( nr.slno );
$("#TextBox1").val(nr.name);
$("#TextBox2").val(nr.country);
}
});
});
$("#btnNewUser").button().on("click", function () {
dialog.dialog("open");
});
function Confirmationbox(obj) {
if (confirm("Do you want to delete this Customer?")) {
var row = $(obj).closest("tr");
row.remove();
}
return true;
}
function updateable(obj) {
var row = $(obj).closest("tr");
var slno = $(row).find("td").eq(0).html();
var name = $(row).find("td").eq(1).html();
var country = $(row).find("td").eq(2).html();
try {
var json = {
slno: slno,
name: name,
country: country
};
editDialog.data('param', json).dialog("open");
event.preventDefault();
} catch (e) {
alert(e);
}
return false;
}
function UpdateRow() {
var slno = $( "#hdslno" ).val();
var m_Name = $( "#TextBox1" ).val();
var m_Country = $( "#TextBox2" ).val();
var row = null;
$( '#gvCustomers1 tr:gt(0)' ).each( function () {
$( this ).find( 'td' ).each( function () {
if ( $( this ).hasClass( "Slno" ) && $( this ).html() == slno ) {
row = $( this ).closest( "tr" );
}
} )
} );
if ( row ) {
$( row ).find( "td" ).eq( 1 ).html( m_Name );
$( row ).find( "td" ).eq( 2 ).html( m_Country );
}
editDialog.dialog( "close" );
return false;
}
function AddRow() {
//Reference the GridView.
var gridView = document.getElementById("<%=gvCustomers1.ClientID %>");
//Reference the TBODY tag.
var tbody = gridView.getElementsByTagName("tbody")[0];
//Reference the first row.
var row = tbody.getElementsByTagName("tr")[1];
//Check if row is dummy, if yes then remove.
if (row.getElementsByTagName("td")[0].innerHTML.replace(/\s/g, '') == "") {
tbody.removeChild(row);
}
//Clone the reference first row.
row = row.cloneNode(true);
var legnth = gridView.rows.length;
SetValue1(row, 0, "Slno", legnth);
//Add the Name value to first cell.
var txtName = document.getElementById("<%=txtName.ClientID %>");
SetValue(row, 1, "name", txtName);
//Add the Country value to second cell.
var txtCountry = document.getElementById("<%=txtCountry.ClientID %>");
SetValue(row, 2, "country", txtCountry);
//Add the row to the GridView.
tbody.appendChild(row);
dialog.dialog("close");
return false;
}
function SetValue(row, index, name, textbox) {
row.cells[index].innerHTML = textbox.value;
textbox.value = "";
}
function SetValue1(row, index, name,leng) {
row.cells[index].innerHTML = leng;
}
</script>
<asp:HiddenField ID="hdTableValues" runat="server" Value="" />
</form>
</body>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace workout
{
public partial class CS1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
DataTable dt = new DataTable();
string query = "SELECT '' Slno, Name, Country FROM dd_Detils";
string constr = "Data Source=localhost;Initial Catalog=DataBase;User ID=sa;Password=globalfocus";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.SelectCommand = cmd;
sda.Fill(dt);
}
}
}
if (dt.Rows.Count == 0)
{
//If no records then add a dummy row.
dt.Rows.Add();
}
gvCustomers1.DataSource = dt;
gvCustomers1.DataBind();
}
protected void Submit(object sender, EventArgs e)
{
int cnt = gvCustomers1.Rows.Count;
if (!string.IsNullOrEmpty(Request.Form["name"]) && !string.IsNullOrEmpty(Request.Form["country"]))
{
//Fetch the Hidden Field values from the Request.Form collection.
string[] names = Request.Form["name"].Split(',');
string[] countries = Request.Form["country"].Split(',');
//Loop through the values and insert into database table.
for (int i = 0; i < names.Length; i++)
{
string constr = "Data Source=localhost;Initial Catalog=Database;User ID=sa;Password=globalfocus";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO dd_Detils VALUES(#Name, #Country)"))
{
cmd.Parameters.AddWithValue("#Name", names[i]);
cmd.Parameters.AddWithValue("#Country", countries[i]);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
//Refresh the page to load GridView with records from database table.
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
}

Open a jQuery (modal form) dialog form in ASP.NET gridview

I relly need your help )) I have a gridview which is bounded to a SQL database. How can I open a pop-up by clicking on image or SQL ID number in my table?
Script v
<script>
$(function () {
var dialog, form,
// From http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#e-mail-state-%28type=email%29
emailRegex = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
name = $("#name"),
email = $("#email"),
password = $("#password"),
allFields = $([]).add(name).add(email).add(password),
tips = $(".validateTips");
function updateTips(t) {
tips
.text(t)
.addClass("ui-state-highlight");
setTimeout(function () {
tips.removeClass("ui-state-highlight", 1500);
}, 500);
}
function checkLength(o, n, min, max) {
if (o.val().length > max || o.val().length < min) {
o.addClass("ui-state-error");
updateTips("Length of " + n + " must be between " +
min + " and " + max + ".");
return false;
} else {
return true;
}
}
function checkRegexp(o, regexp, n) {
if (!(regexp.test(o.val()))) {
o.addClass("ui-state-error");
updateTips(n);
return false;
} else {
return true;
}
}
function addUser() {
var valid = true;
allFields.removeClass("ui-state-error");
valid = valid && checkLength(name, "username", 3, 16);
valid = valid && checkLength(email, "email", 6, 80);
valid = valid && checkLength(password, "password", 5, 16);
valid = valid && checkRegexp(name, /^[a-z]([0-9a-z_\s])+$/i, "Username may consist of a-z, 0-9, underscores, spaces and must begin with a letter.");
valid = valid && checkRegexp(email, emailRegex, "eg. ui#jquery.com");
valid = valid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");
if (valid) {
$("#users tbody").append("<tr>" +
"<td>" + name.val() + "</td>" +
"<td>" + email.val() + "</td>" +
"<td>" + password.val() + "</td>" +
"</tr>");
dialog.dialog("close");
}
return valid;
}
dialog = $("#dialog-form").dialog({
autoOpen: false,
height: 400,
width: 350,
modal: true,
buttons: {
"Create an account": addUser,
Cancel: function () {
dialog.dialog("close");
}
},
close: function () {
form[0].reset();
allFields.removeClass("ui-state-error");
}
});
form = dialog.find("form").on("submit", function (event) {
event.preventDefault();
addUser();
});
$("#create-user").button().on("click", function () {
dialog.dialog("open");
});
});
</script>
This is my gridview:
<asp:GridView id="Objektkatalog" runat="server" OnClick = "Page_Changed"
AllowPaging="true" PageSize="4" DataSourceID="SqlDataSource2"
DataKeyNames="ObjektID" AutoGenerateColumns="false"
OnRowDataBound="GridView1_RowDataBound">
<columns>
<asp:TemplateField>
<ItemTemplate>
Nr. <%#Eval("ObjektID")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" Height="55px" Width="55px" ImageUrl='<%# Eval("Picture","~/Objekte/{0}") %>' /> //it comes to a second itemTemplate, dono why i cant add this in code section...
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
And well, if I use this button
<button id="create-user">Create new user</button>
then it works fine and I open my EditTmplate, where I can change all data in my SQL database, but I have to do the same pop up by clicking on every element of my table; I know its a couple of lines or just 1 command to change, but id very bad in JS, jQuery etc.=) I will be very glad for your help.
I still made some picture to explain it better =) http://ipic.su/img/img7/fs/dsadsadsada.1406036339.jpg
Put the code for opening popup in below function -
$(document).on("click", "[id*=idViewPopup]", function () {
});
Here [id*=idViewPopup] is nothing but ID of the object in the GridView. so, when I click on the image with ID = idViewPopup, the model popup will be displayed.
Check below link for detailed example -
http://www.aspsnippets.com/Articles/Display-GridView-Row-details-inside-jQuery-Dialog-Modal-Popup-in-ASPNet.aspx

AngularJS ng-grid does not work after PostBack in ASP.NET page

I have a ng-grid object that loads data from a JSON string into a ASP.NET page.
The User can select one or more rows than click "confirm" button.
When "confirm" button il clicked I check, in code-behind, how many rows are selected.
If no rows are selected I show a messagebox to the user, otherwise I save the data.
The problem is that pressing "confirm" button if no rows are selected, make impossibile to get any data from the grid so I need to reload the page manually.
It seems that the PostBack is partial and does not update all the page.
Here some code from aspx page
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function ($scope) {
$scope.multiSelect = false;
$(".gridStyle").keydown(function (e) {
if ((e.keyCode == 16 || e.keyCode == 17) && !$scope.multiSelect) {
$scope.multiSelect = true;
}
});
$(".gridStyle").keyup(function (e) {
if ((e.keyCode == 16 || e.keyCode == 17)) {
$scope.multiSelect = false;
}
});
$scope.mySelections = [];
$scope.myData = myJsonData;
$scope.myColDef = myColumnDef;
$scope.enableRowSelection = myEnableRowSelection;
$scope.checkboxHeaderTemplate = myCheckboxHeaderTemplate;
$scope.gridOptions = {
data: 'myData',
columnDefs: $scope.myColDef,
selectedItems: $scope.mySelections,
checkboxHeaderTemplate: $scope.checkboxHeaderTemplate,
showSelectionCheckbox: $scope.enableRowSelection,
selectWithCheckboxOnly: false,
enableRowSelection: $scope.enableRowSelection,
beforeSelectionChange: function (rowItem, event) {
if (!$scope.multiSelect) {
angular.forEach($scope.myData, function (data, index) {
$scope.gridOptions.selectRow(index, false);
});
}
return true;
}
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="msgboxpanel" runat="server"></div>
<div class="gridStyle" ng-grid="gridOptions"></div>
<input type="text" runat="server" name="selectedItems" id="selectedItems" value="{{gridOptions.selectedItems}}" />
<asp:Button runat="server" Width="200px" OnClick="Button1_Click" ID="okButton" CssClass="submit" Text="Submit" meta:resourcekey="b_Submit" />
</div>
</form>
</body>
Here Code Behind:
protected void Button1_Click(object sender, EventArgs e)
{
bool LoadErr = false;
var jarray = JsonConvert.DeserializeObject<List<DummyTomTom>>(selectedTomTom.Value.ToString());
if (jarray.Count > 0)
{
LoadErr = false;
foreach (var item in jarray)
{
addTomTomToUser((DummyTomTom)item, (bool)checkAutomaticallyCreate.Checked);
}
}
else
{
LoadErr = true;
MessageBox msgbox = new MessageBox("msgbox\\msgbox.tpl", "../");
msgbox.SetTitle(GetLocalResourceObject("t_noItemsSelectedMessage").ToString());
msgbox.SetIcon("../msgbox/uyari.gif");
msgbox.SetMessage(GetLocalResourceObject("l_noItemsSelectedMessage").ToString());
msgbox.SetOKButton();
msgboxpanel.InnerHtml = msgbox.ReturnObject();
msgboxpanel.Visible = true;
showMsg = true;
}
}
Any idea?
Many thanks !
I am ashamed... after hours I found the answer...:
The problem is that selectedItems field, after postback
In codebehind, in the "else", I added this simple row:
selectedItems.Value="{{gridOptions.selectedItems}}";
thank you !

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.

Categories