Dynamic grid on ASP.NET - c#

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

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.

How to Insert and edit from the grid-view on run time using resource file

I am working on resource files. I can now read resx file and get it populate the data into the grid-view. now here is my question now,
On a run time, i want to be able to edit the columns and also be able to click empty columns and click save to save my changes. How do i do that. please help me as i have tried many examples and it didn't work.
my code below,
private void btnNewfile_Click(object sender, EventArgs e)
{
for (int i = 0; i < oDataSet.Tables[2].Rows.Count; i++)
{
string comment = oDataSet.Tables["data"].Rows[i][2].ToString();
string font = Between(comment, "[Font]", "[/Font]");
string datestamp = Between(comment, "[DateStamp]", "[/DateStamp]");
string commentVal = Between(comment, "[Comment]", "[/Comment]");
string[] row = new string[] { oDataSet.Tables["data"].Rows[i][0].ToString(), oDataSet.Tables["data"].Rows[i][1].ToString(), font, datestamp, commentVal };
Gridview_Output.Rows.Add(row);
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(PathSelection);
}
Save button(the user must be able to save the file created or edit to any location (C drive))
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save Resource Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "resx";
saveFileDialog1.Filter = "Save Resource Files (*.resx)|*.resx";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
//nere i need the user to save to any location he want not textbox.
txtOutputfile.Text = saveFileDialog1.FileName;
}
//oDataSet.Tables.Add("Data");
oDataSet.WriteXml(PathSelection);
versionIncrement();
MessageBox.Show("Successfully added ");
}
See if the below code helps.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="UpdateResource.aspx.cs" Inherits="UpdateResource" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Update Resource</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
//Enable Disable all TextBoxes when Header Row CheckBox is checked.
$("[id*=chkHeader]").bind("click", function () {
var chkHeader = $(this);
//Find and reference the GridView.
var grid = $(this).closest("table");
//Loop through the CheckBoxes in each Row.
$("td", grid).find("input[type=checkbox]").each(function () {
//If Header CheckBox is checked.
//Then check all CheckBoxes and enable the TextBoxes.
if (chkHeader.is(":checked")) {
$(this).attr("checked", "checked");
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#00000" });
$("input[type=text]", td).removeAttr("disabled");
} else {
$(this).removeAttr("checked");
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#FFF" });
$("input[type=text]", td).attr("disabled", "disabled");
}
});
});
//Enable Disable TextBoxes in a Row when the Row CheckBox is checked.
$("[id*=chkRow]").bind("click", function () {
//Find and reference the GridView.
var grid = $(this).closest("table");
//Find and reference the Header CheckBox.
var chkHeader = $("[id*=chkHeader]", grid);
//If the CheckBox is Checked then enable the TextBoxes in thr Row.
if (!$(this).is(":checked")) {
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#FFF" });
$("input[type=text]", td).attr("disabled", "disabled");
} else {
var td = $("td", $(this).closest("tr"));
td.css({ "background-color": "#00000" });
$("input[type=text]", td).removeAttr("disabled");
}
//Enable Header Row CheckBox if all the Row CheckBoxes are checked and vice versa.
if ($("[id*=chkRow]", grid).length == $("[id*=chkRow]:checked", grid).length) {
chkHeader.attr("checked", "checked");
} else {
chkHeader.removeAttr("checked");
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="cmbResources" runat="server" AutoPostBack="true" OnSelectedIndexChanged="cmbResources_SelectedIndexChanged"
Width="275px">
</asp:DropDownList>
<br />
<br />
<asp:DataGrid ID="gridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
BorderColor="Black" BorderStyle="Groove" ForeColor="#333333" Width="500px">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<%= ++indexNum %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="English Word">
<ItemTemplate>
<%# DataBinder.Eval(Container,"DataItem.Key") %>
</ItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="Translated Word">
<ItemTemplate>
<%--<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.Value") %>'
BorderStyle="Groove" disabled="disabled"></asp:TextBox>--%>
<asp:TextBox ID="txtTrans" runat="server" Text='<%# DataBinder.Eval(Container,"DataItem.Value") %>'
Enabled="false" BorderStyle="Groove"></asp:TextBox>
</ItemTemplate>
</asp:TemplateColumn>
<%--<asp:TemplateColumn>
<ItemTemplate>
<a href='editresource.aspx?key=<%# DataBinder.Eval(Container,"DataItem.Key") %>&file=<%=cmbResources.SelectedItem.Text %>&id=<%=indexNum - 1 %>'>
Edit</a>
</ItemTemplate>
</asp:TemplateColumn>--%>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
<FooterStyle Font-Bold="True" ForeColor="White" />
<SelectedItemStyle Font-Bold="True" ForeColor="Navy" />
<PagerStyle ForeColor="#333333" HorizontalAlign="Center" />
<ItemStyle ForeColor="#333333" Font-Size="Small" Font-Names="verdana" />
<HeaderStyle Font-Bold="True" />
</asp:DataGrid>
<br />
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Resources;
using System.IO;
using System.Xml;
public partial class UpdateResource : System.Web.UI.Page
{
public int indexNum = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//string resourcespath = Request.PhysicalApplicationPath + "App_GlobalResources";
//DirectoryInfo dirInfo = new DirectoryInfo(resourcespath);
//foreach (FileInfo filInfo in dirInfo.GetFiles())
//{
// string filename = filInfo.Name;
// cmbResources.Items.Add(filename);
//}
//cmbResources.Items.Insert(0, new ListItem("Select a Resource File"));
string[] filePaths = Directory.GetFiles(#"C:\Users\D1956\Desktop\ResourceEdit", "*.aspx");
foreach (string file in filePaths)
{
string[] f = file.Split(new char[] { '\\' });
cmbResources.Items.Add(f[f.Length - 1]);
}
}
}
protected void cmbResources_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbResources.SelectedIndex != 0)
{
string filename = Request.PhysicalApplicationPath + "App_GlobalResources\\" + cmbResources.SelectedItem.Text;
Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
ResXResourceReader RrX = new ResXResourceReader(stream);
IDictionaryEnumerator RrEn = RrX.GetEnumerator();
SortedList slist = new SortedList();
while (RrEn.MoveNext())
{
slist.Add(RrEn.Key, RrEn.Value);
}
RrX.Close();
stream.Dispose();
gridView1.DataSource = slist;
gridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string filename = Request.PhysicalApplicationPath + "App_GlobalResources\\" + cmbResources.SelectedItem.Text;
string filename1 = filename.Remove(filename.Length - 5);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(filename);
XmlNodeList nlist = xmlDoc.GetElementsByTagName("data");
for (int i = 0; i < gridView1.Items.Count; i++)
{
CheckBox chkItem = (CheckBox)gridView1.Items[i].FindControl("chkRow");
if (chkItem.Checked)
{
XmlNode childnode = nlist.Item(i);
XmlNode lastnode = childnode.SelectSingleNode("value");
TextBox txtTran = (TextBox)gridView1.Items[i].FindControl("txtTrans");
lastnode.InnerText = txtTran.Text.ToString();
}
}
xmlDoc.Save(filename1 + "_1" + ".resx");
}
}
You may have to edit the !IsPostback part.

Adding polylines to Bing maps programmatically

I have routes names in my dropdownlist and arrays with lat/log (polylines) with correspondence by event. How to send this lat/log from code behind to javascript?
<head>
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
<script type="text/javascript">
function GetMap() {
// Initialize the map
var mapOptions = {
credentials: "xxxx",
center: new Microsoft.Maps.Location( 9.74, 2.425),
mapTypeId: Microsoft.Maps.MapTypeId.road,
zoom: 13,
showScalebar: false
}
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);
var lineVertices = new Array(new Microsoft.Maps.Location(<%#new pts%>));
var line = new Microsoft.Maps.Polyline(lineVertices);
map.entities.push(line);
}
</script>
<style type="text/css">
#form1
{
width: 480px;
}
</style>
<body onload="GetMap();" style="height: 18px; width: 480px">
<form id="form1" runat="server">
<div id='listDiv' style="width:480px; height:30px" >
<asp:DropDownList ID="listPicker" runat="server" Height="25px" Width="218px"
onselectedindexchanged="listPicker_SelectedIndexChanged">
</asp:DropDownList>
</div>
<div id='mapDiv' style="position:absolute; width:480px; height:740px; top: 38px; ">
</div>
</form>
protected void listPicker_SelectedIndexChanged(object sender, EventArgs e)
{
if (listPicker.SelectedIndex == 1)
{
pts = new double[,] {
{ 9.6990549318566, 2.4374476373222},
{ 9.6991218770296, 2.4379291260322},
{ 9.6994116428257, 2.4376508334228},
{ 9.6995069262757, 2.4356545805958},
{ 9.6999728977379, 2.4356384873417},
{ 9.6999845469968, 2.4326612353352},
{ 9.7056459228308, 2.432768526198},
{ 9.7088142924775, 2.4295498753801},
{ 9.7228377868168, 2.4293138409868},
{ 9.7228098349562, 2.4276401425615}};
}else{...}
}
There is a way to send this points to js?
You can try
Dim oGeocodeList As New List(Of [String])()
oGeocodeList.Add(" '37.968002524107035, 23.702445030212402' ")
oGeocodeList.Add(" '37.969, 23.705445030212402' ")
oGeocodeList.Add(" '37.97, 23.709445030212402' ")
Dim geocodevalues = String.Join(",", oGeocodeList.ToArray())
ClientScript.RegisterArrayDeclaration("locationList", geocodevalues)
and in javacrtipt
var locationList;
I am sorry for the vb code.

PagedDataSource not paging

i have serched all over the web and didnt find anything like what i am doing or any solution to my problam.
i have an xsd file that connects to mdb and i want to show 10 resukts at a time and to have the ability to page throw all the results,for now the status is that i get 62 results per page and when i am trying to go to the next page i dont recive any results.
what is wrong in my code
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="MainPage.aspx.cs"
Inherits="FaceBookSearchN.MainPage" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<%--<%# Register Src="~/ResultsControl.ascx" TagPrefix="Results" TagName="ResultsControl" %>--%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<style type="text/css">
.accordionHeader
{
border: 1px solid blue;
color: White;
background-color: #5078B3;
font-family: Arial,Sans-Serif;
font-size: 12px;
font-weight: bold;
padding: 5px;
margin-top: 5px;
cursor: pointer;
}
.accordionHeader a, .accordionHeaderSelected a
{
color: #ffffff;
background: none;
text-decoration: none;
}
.accordionHeader a:hover, .accordionHeaderSelected a:hover
{
background: none;
text-decoration: underline;
}
.accordionHeaderSelected
{
border: 1px solid #2f4f4f;
color: White;
background-color: #5078B3;
font-family: Arial, Sans-Serif;
font-size: 12px;
font-weight: bold;
padding: 5px;
cursor: pointer;
}
.accordionContent
{
background-color: White;
border: 1px solid,#2f4f4f;
border-top: none;
padding: 5px;
padding-top: 10px;
}
</style>
<title></title>
</head>
<body dir="rtl">
<form id="form1" runat="server">
<div>
<table width="520px">
<tr>
<td>
<table width="100%">
<tr>
<td>
<asp:Label runat="server" Text="תחום" ID="lblProffesion"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DropDownList runat="server" ID="ddlProffesion" DataTextField="profession_name"
DataValueField="profession_id" OnSelectedIndexChanged="ddlProffesion_SelectedIndexChanged"
AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
</table>
</td>
<td>
<table width="100%">
<tr>
<td>
<asp:Label runat="server" Text="אזור" ID="lblArea"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DropDownList runat="server" ID="ddlArea" DataValueField="id_area" DataTextField="name_area"
AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="100%">
<tr>
<td>
<asp:Label runat="server" Text="תפקיד" ID="lblSubProffesion"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:DropDownList runat="server" ID="ddlSubProffesion" DataValueField="tat_pofession_id"
DataTextField="tat_pofession_name" AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
</table>
</td>
<td>
<table width="100%">
<tr>
<td>
<asp:Label runat="server" Text="אזור כתיבה חופשי" ID="lblFreetext"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:TextBox runat="server" ID="txtFreetext"></asp:TextBox>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button runat="server" Text="חיפוש" ID="btnSearch" OnClick="btnSearch_Click" />
</td>
</tr>
</table>
<div style="width: 520px">
<table width="520px" id="tblHeader" runat="server" style="background-color: #5078B3;
height: 25px">
<tr>
<td>
<asp:Label runat="server" ID="lblJobNum" Text="מס' משרה"></asp:Label>
</td>
<td>
<asp:Label runat="server" ID="lblJobName" Text="שם משרה"></asp:Label>
</td>
<td>
<asp:Label runat="server" ID="lblJobArea" Text="אזור עבודה"></asp:Label>
</td>
</tr>
</table>
<asp:Accordion ID="Accordion1" runat="server" AutoSize="None" FramesPerSecond="40" SelectedIndex="0" TransitionDuration="100"
FadeTransitions="true" RequireOpenedPane="true" SuppressHeaderPostbacks="true"
ContentCssClass="accordionContent" HeaderCssClass="accordionHeader" HeaderSelectedCssClass="accordionHeaderSelected">
</asp:Accordion>
<asp:Label ID="lblCurrentPage" runat="server"></asp:Label>
<asp:Button ID="btnPrev" runat="server" Text=" << " />
<asp:Button ID="btnNext" runat="server" Text=" >> " />
</div>
</div>
<asp:ToolkitScriptManager ID="Toolkitscriptmanager1" runat="server">
</asp:ToolkitScriptManager>
</form>
</body>
</html>
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.Web.UI.HtmlControls;
namespace FaceBookSearchN
{
public partial class MainPage : System.Web.UI.Page
{
private DataConnectionTableAdapters.table_professionTableAdapter adapterProf;
private DataConnectionTableAdapters.table_profession_tatTableAdapter adapterSubProf;
private DataConnectionTableAdapters.table_areaTableAdapter adapterArea;
private DataConnectionTableAdapters.ordersTableAdapter adapterOrdersNoParams;
private DataConnectionTableAdapters.ordersWithParamsTableAdapter adapterOrdersWithParams;
private DataConnection.table_professionDataTable profDT;
private DataConnection.table_profession_tatDataTable SubProfDT;
private DataConnection.table_areaDataTable areaDT;
private DataConnection.ordersDataTable ordersNoParamsDT;
private DataConnection.ordersWithParamsDataTable ordersWithParamsDT;
PagedDataSource pds;
public int CurrentPage
{
get
{
object o = this.ViewState["CurrentPage"];
if (o == null)
return 0;
else
return (int)o;
}
set
{
this.ViewState["CurrentPage"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
OnLoad();
}
}
protected void OnLoad()
{
tblHeader.Visible = false;
profDT = new DataConnection.table_professionDataTable();
adapterProf = new DataConnectionTableAdapters.table_professionTableAdapter();
areaDT = new DataConnection.table_areaDataTable();
adapterArea = new DataConnectionTableAdapters.table_areaTableAdapter();
adapterProf.Fill(profDT);
adapterArea.Fill(areaDT);
//adapter.Fill(SubProfDT);
ddlProffesion.DataSource = profDT;
ddlProffesion.DataBind();
ddlProffesion.Items.Insert(0,new ListItem("בחר מקצוע", "0"));
ddlArea.DataSource = areaDT;
ddlArea.DataBind();
ddlArea.Items.Insert(0, new ListItem("בחר אזור", "0"));
ddlSubProffesion.Items.Insert(0, new ListItem("בחר תת מקצוע", "0"));
}
protected void ddlProffesion_SelectedIndexChanged(object sender, EventArgs e)
{
SubProfDT = new DataConnection.table_profession_tatDataTable();
adapterSubProf = new DataConnectionTableAdapters.table_profession_tatTableAdapter();
adapterSubProf.GetDataByID(int.Parse(ddlProffesion.SelectedValue));
SubProfDT = adapterSubProf.GetDataByID(int.Parse(ddlProffesion.SelectedValue));
ddlSubProffesion.DataSource = SubProfDT;
ddlSubProffesion.DataBind();
//ddlSubProffesion.Items.Insert(0, new ListItem("בחר תת מקצוע", "0"));
}
protected void btnSearch_Click(object sender, EventArgs e)
{
tblHeader.Visible = true;
if (int.Parse(ddlProffesion.SelectedValue) == 0 && int.Parse(ddlArea.SelectedValue) == 0)
{
ordersNoParamsDT = new DataConnection.ordersDataTable();
adapterOrdersNoParams = new DataConnectionTableAdapters.ordersTableAdapter();
adapterOrdersNoParams.FillOrdersNoParams(ordersNoParamsDT);
DataTable dt = new DataTable();
dt = ordersNoParamsDT;
pds = new PagedDataSource();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 10;
pds.CurrentPageIndex = CurrentPage;
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " " + "of" + " " + pds.PageCount.ToString();
btnPrev.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
ViewState["totalpages"] = pds.PageCount;
for (int i = 0; i < pds.PageCount; i++)
{
FileUpload fu = new FileUpload();
Button btnSubmit = new Button();
btnSubmit.Text = "שלח קורות חיים";
AjaxControlToolkit.AccordionPane pn;
pn = new AjaxControlToolkit.AccordionPane();
pn.ID = "pane" + i;
Label lblTitle = new Label();
Label lblJobName = new Label();
Label lblDesc = new Label();
lblTitle.Text = dt.Rows[i]["order_id"].ToString();
lblJobName.Text = dt.Rows[i]["description"].ToString();
//lblDesc.Text = dt.Rows[i]["description"].ToString();
//Accordion1.DataSource = pds;
//Accordion1.DataBind();
pn.HeaderContainer.Controls.Add(lblTitle);
pn.HeaderContainer.Controls.Add(lblJobName);
HtmlTable tableDesc = new HtmlTable();
HtmlTableRow row;
HtmlTableCell cell;
cell = new HtmlTableCell();
row = new HtmlTableRow();
cell.InnerHtml = dt.Rows[i]["notes"].ToString();
row.Cells.Add(cell);
tableDesc.Rows.Add(row);
fu.Width = Unit.Percentage(100.00);
pn.ContentContainer.Controls.Add(lblDesc);
pn.ContentContainer.Controls.Add(tableDesc);
pn.ContentContainer.Controls.Add(fu);
pn.ContentContainer.Controls.Add(btnSubmit);
Accordion1.Panes.Add(pn);
}
//int i = 0;
//foreach (DataRow dr in ordersNoParamsDT)
//{
// FileUpload fu = new FileUpload();
// AjaxControlToolkit.AccordionPane pn;
// pn = new AjaxControlToolkit.AccordionPane();
// pn.ID = "pane" + i;
// Label lblTitle = new Label();
// Label lblDesc = new Label();
// lblTitle.Text = dr["order_id"].ToString();
// //lblTitle.Text = "מס' משרה" +"|" + "שם משרה" +"|"+ "אזור עבודה"+ "|";
// pn.HeaderContainer.Controls.Add(lblTitle);
// lblDesc.Text = dr["description"].ToString();
// //pn.ContentContainer.Controls.Add(lblDesc);
// HtmlTable tableDesc = new HtmlTable();
// HtmlTableRow row;
// HtmlTableCell cell;
// HtmlTableCell cell2;
// cell = new HtmlTableCell();
// cell2 = new HtmlTableCell();
// row = new HtmlTableRow();
// cell.InnerHtml = dr["notes"].ToString();
// fu.Width = Unit.Percentage(100.00);
// cell2.Controls.Add(fu);
// row.Cells.Add(cell);
// tableDesc.Rows.Add(row);
// pn.ContentContainer.Controls.Add(tableDesc);
// Accordion1.Panes.Add(pn);
// i++;
//}
//Accordion1.DataSource = new System.Data.DataTableReader(ordersNoParamsDT);
//Accordion1.DataBind();
//ucResults.Proffesion = int.Parse(ddlProffesion.SelectedValue);
//ucResults.SubProffesion = 0;
//ucResults.Area = int.Parse(ddlArea.SelectedValue);
}
else
{
// ucResults.Proffesion = int.Parse(ddlProffesion.SelectedValue);
// ucResults.SubProffesion = int.Parse(ddlSubProffesion.SelectedValue);
// ucResults.Area = int.Parse(ddlArea.SelectedValue);
}
}
private void btnPrev_Click(object sender, System.EventArgs e)
{
// Set viewstate variable to the previous page
CurrentPage -= 1;
// Reload control
//ItemsGet();
}
private void btnNext_Click(object sender, System.EventArgs e)
{
// Set viewstate variable to the next page
CurrentPage += 1;
// Reload control
//ItemsGet();
}
}
}
Your OnLoad() method only triggers during the first page load. The data needs to be rebound every time the page is changed. Try removing the if(!IsPostBack) from the Page_Load method and see if it works.

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