<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Create Docket</title>
<script type = "text/javascript">
var tb1 = document.getElementById('txtVehicleNo');
var tb2 = document.getElementById('txtVehicleNo1');
tb1.value = tb2.value;
</script>
<script type = "text/javascript">
function Check_Click(objRef) {
//Get the Row based on checkbox
var row = objRef.parentNode.parentNode;
//Get the reference of GridView
var GridView = row.parentNode;
//Get all input elements in Gridview
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
//The First element is the Header Checkbox
var headerCheckBox = inputList[0];
//Based on all or none checkboxes
//are checked check/uncheck Header Checkbox
var checked = true;
if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox)
{
if (!inputList[i].checked) {
checked = false;
break;
}
}
}
headerCheckBox.checked = checked;
}
function checkAll(objRef) {
var GridView = objRef.parentNode.parentNode.parentNode;
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
var row = inputList[i].parentNode.parentNode;
if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
if (objRef.checked) {
inputList[i].checked = true;
}
else {
if (row.rowIndex % 2 == 0) {
row.style.backgroundColor = "#C2D69B";
}
else {
row.style.backgroundColor = "white";
}
inputList[i].checked = false;
}
}
}
}
</script>
</head>
<body style="height: 451px; width: 860px">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:GridView ID="gvAll" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" AllowPaging ="true"
OnPageIndexChanging = "OnPaging" PageSize = "10" Height="30px" Width="341px">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"
AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "DocketNo" HeaderText = "DocketNo"
HtmlEncode = "false" />
<asp:BoundField DataField = "Date" HeaderText = "Date"
HtmlEncode = "false" />
<asp:BoundField DataField = "BranchCode" HeaderText = "BranchCode"
HtmlEncode = "false" />
<asp:BoundField DataField = "To" HeaderText = "To"
HtmlEncode = "false" />
<asp:BoundField DataField = "PKTS" HeaderText = "No of pkg"
HtmlEncode = "false" />
<asp:BoundField DataField = "ActWt" HeaderText = "ActWt"
HtmlEncode = "false" />
<asp:BoundField DataField = "ChargeWt" HeaderText = "ChargeW"
HtmlEncode = "false" />
<asp:BoundField DataField = "Description" HeaderText = "Description"
HtmlEncode = "false" />
<asp:BoundField DataField = "Remarks" HeaderText = "Remarks"
HtmlEncode = "false" />
<asp:BoundField DataField = "Mode" HeaderText = "Mode"
HtmlEncode = "false" />
<asp:BoundField DataField = "ChallanNo" HeaderText = "ChallanNo"
HtmlEncode = "false" />
<asp:BoundField DataField = "VehicleNo" HeaderText = "VehicleNo"
HtmlEncode = "false" />
<asp:BoundField DataField = "ChallanDate" HeaderText = "ChallanDate"
HtmlEncode = "false" />
<asp:BoundField DataField = "RChallanDate" HeaderText = "RChallanDate"
HtmlEncode = "false" />
<asp:BoundField DataField = "FromHub" HeaderText = "FromHub"
HtmlEncode = "false" />
<asp:BoundField DataField = "ToHub" HeaderText = "ToHub"
HtmlEncode = "false" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
<br />
<table border="1">
<tr>
<td>
<asp:Label ID="lblMode" Text="Mode" runat="server"></asp:Label>
<br />
<asp:DropDownList ID="dropdownMode" runat="server">
<asp:ListItem>Air</asp:ListItem>
<asp:ListItem>Surface</asp:ListItem>
<asp:ListItem>Rail</asp:ListItem>
</asp:DropDownList>
</td>
This is the textbox which I'm using to put the value of vehicle number into the GridView gvSelected
<tr>
<td>
<asp:Label ID="lblChallanNo" Text="Challan No." runat="server"></asp:Label>
<asp:TextBox ID="txtChallanNo" runat="server"></asp:TextBox>
</td>
<td>
<asp:Label ID="lblLHCNo" Text="LHCNo" runat="server"></asp:Label>
<asp:TextBox ID="txtLHCNo" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="FindLHCNo" Text="Find" runat="server" OnClick="FindLHCNo_Click" />
</td>
<td>
<asp:Label ID="Label1" runat="server"></asp:Label>
</td>
<td>
<asp:Label ID="lblLHCDate" Text="LHC Date" runat="server"></asp:Label>
<asp:TextBox ID="txtLHCDate" runat="server"></asp:TextBox>
</td>
</tr>
</table>
<br />
<p align="center">
<asp:Button ID="Update" runat="server" Text="Update Challan" OnClick="Update_Click" /> </p>
<asp:GridView ID="gvSelected" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" EmptyDataText = "" >
<Columns>
<asp:TemplateField HeaderText="DocketNo"
SortExpression="DocketNo">
<ItemTemplate>
<asp:TextBox ID="txtDocketNo" runat="server" Width="50px"
Text='<%# Bind("DocketNo") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date"
SortExpression="Date">
<ItemTemplate>
<asp:TextBox ID="txtDate" runat="server" Width="50px"
Text='<%# Bind("Date") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="BranchCode"
SortExpression="BranchCode">
<ItemTemplate>
<asp:TextBox ID="txtBranchCode" runat="server" Width="50px"
Text='<%# Bind("BranchCode") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="To"
SortExpression="To">
<ItemTemplate>
<asp:TextBox ID="txtTo" runat="server" Width="50px"
Text='<%# Bind("To") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PKTS"
SortExpression="PKTS">
<ItemTemplate>
<asp:TextBox ID="txtPKTS" runat="server" Width="50px"
Text='<%# Bind("PKTS") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ActWt"
SortExpression="ActWt">
<ItemTemplate>
<asp:TextBox ID="txtActWt" runat="server" Width="50px"
Text='<%# Bind("ActWt") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ChargeWt"
SortExpression="ChargeWt">
<ItemTemplate>
<asp:TextBox ID="txtChargeWt" runat="server" Width="50px"
Text='<%# Bind("ChargeWt") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description"
SortExpression="Description">
<ItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" Width="50px"
Text='<%# Bind("Description") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remarks"
SortExpression="Remarks">
<ItemTemplate>
<asp:TextBox ID="txtRemarks" runat="server" Width="50px"
Text='<%# Bind("Remarks") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Mode"
SortExpression="Mode">
<ItemTemplate>
<asp:TextBox ID="txtMode" runat="server" Width="50px"
Text='<%# Bind("Mode") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ChallanNo"
SortExpression="ChallanNo">
<ItemTemplate>
<asp:TextBox ID="txtChallanNo" runat="server" Width="50px"
Text='<%# Bind("ChallanNo") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="VehicleNo"
SortExpression="VehicleNo">
<ItemTemplate>
<asp:TextBox ID="txtVehicleNo1" runat="server" Width="50px"
Text='<%# Bind("VehicleNo") %>'
ReadOnly="false" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ChallanDate"
SortExpression="ChallanDate">
<ItemTemplate>
<asp:TextBox ID="txtChallanDate" runat="server" Width="50px"
Text='<%# Bind("ChallanDate") %>'
ReadOnly="false" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="RChallanDate"
SortExpression="RChallanDate">
<ItemTemplate>
<asp:TextBox ID="txtRChallanDate" runat="server" Width="50px"
Text='<%# Bind("RChallanDate") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FromHub"
SortExpression="FromHub">
<ItemTemplate>
<asp:TextBox ID="txtFromHub" runat="server" Width="50px"
Text='<%# Bind("FromHub") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ToHub"
SortExpression="ToHub">
<ItemTemplate>
<asp:TextBox ID="txtToHub" runat="server" Width="50px"
Text='<%# Bind("ToHub") %>'
ReadOnly="true" ForeColor="Blue"
BorderStyle="none" BorderWidth="0px">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:amitpandeyConnectionString %>" SelectCommand="SELECT [BranchCode], [Date], [DocketNo], [To], [PKTS], [ActWt], [ChargeWt], [Mode], [ChallanNo], [VehicleNo], [ChallanDate], [Description], [RChallanDate], [Remarks], [FromHub], [ToHub] FROM [CreateDocket]"></asp:SqlDataSource>
</div>
</form>
</body>
</html>
C# Code
public partial class FNC : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPrimaryGrid();
BindSecondaryGrid();
}
}
private void BindPrimaryGrid()
{
string constr = ConfigurationManager.ConnectionStrings["amitpandeyConnectionString"].ConnectionString;
string query = "select * from CreateDocket";
SqlConnection con = new SqlConnection(constr);
SqlDataAdapter sda = new SqlDataAdapter(query, con);
DataTable dt = new DataTable();
sda.Fill(dt);
gvAll.DataSource = dt;
gvAll.DataBind();
}
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GetData();
gvAll.PageIndex = e.NewPageIndex;
BindPrimaryGrid();
SetData();
}
private void GetData()
{
DataTable dt;
if (ViewState["SelectedRecords"] != null)
dt = (DataTable)ViewState["SelectedRecords"];
else
dt = CreateDataTable();
CheckBox chkAll = (CheckBox)gvAll.HeaderRow.Cells[0].FindControl("chkAll");
for (int i = 0; i < gvAll.Rows.Count; i++)
{
if (chkAll.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
gvAll.Rows[i].Visible = false;
}
else
{
CheckBox chk = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if (chk.Checked)
{
dt = AddRow(gvAll.Rows[i], dt);
gvAll.Rows[i].Visible = false;
}
else
{
dt = RemoveRow(gvAll.Rows[i], dt);
}
}
}
ViewState["SelectedRecords"] = dt;
}
private void SetData()
{
CheckBox chkAll = (CheckBox)gvAll.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
if (ViewState["SelectedRecords"] != null)
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
for (int i = 0; i < gvAll.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvAll.Rows[i].Cells[0].FindControl("chk");
if (chk != null)
{
DataRow[] dr = dt.Select("DocketNo = '" + gvAll.Rows[i].Cells[1].Text + "'");
chk.Checked = dr.Length > 0;
if (!chk.Checked)
{
chkAll.Checked = false;
}
}
}
}
}
private DataTable CreateDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("DocketNo");
dt.Columns.Add("Date");
dt.Columns.Add("BranchCode");
dt.Columns.Add("To");
dt.Columns.Add("PKTS");
dt.Columns.Add("ActWt");
dt.Columns.Add("ChargeWt");
dt.Columns.Add("Description");
dt.Columns.Add("Remarks");
dt.Columns.Add("Mode");
dt.Columns.Add("ChallanNo");
dt.Columns.Add("VehicleNo");
dt.Columns.Add("ChallanDate");
dt.Columns.Add("RChallanDate");
dt.Columns.Add("FromHub");
dt.Columns.Add("ToHub");
dt.AcceptChanges();
return dt;
}
private DataTable AddRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("DocketNo = '" + gvRow.Cells[1].Text + "'");
if (dr.Length <= 0)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count - 1]["BranchCode"] = gvRow.Cells[3].Text;
dt.Rows[dt.Rows.Count - 1]["Date"] = gvRow.Cells[2].Text;
dt.Rows[dt.Rows.Count - 1]["DocketNo"] = gvRow.Cells[1].Text;
dt.Rows[dt.Rows.Count - 1]["To"] = gvRow.Cells[4].Text;
dt.Rows[dt.Rows.Count - 1]["PKTS"] = gvRow.Cells[5].Text;
dt.Rows[dt.Rows.Count - 1]["ActWt"] = gvRow.Cells[6].Text;
dt.Rows[dt.Rows.Count - 1]["ChargeWt"] = gvRow.Cells[7].Text;
dt.Rows[dt.Rows.Count - 1]["Description"] = gvRow.Cells[8].Text;
dt.Rows[dt.Rows.Count - 1]["Remarks"] = gvRow.Cells[9].Text;
dt.Rows[dt.Rows.Count - 1]["Mode"] = gvRow.Cells[10].Text;
dt.Rows[dt.Rows.Count - 1]["ChallanNo"] = gvRow.Cells[11].Text;
dt.Rows[dt.Rows.Count - 1]["VehicleNo"] = gvRow.Cells[12].Text;
dt.Rows[dt.Rows.Count - 1]["ChallanDate"] = gvRow.Cells[13].Text;
dt.Rows[dt.Rows.Count - 1]["RChallanDate"] = gvRow.Cells[14].Text;
dt.Rows[dt.Rows.Count - 1]["FromHub"] = gvRow.Cells[15].Text;
dt.Rows[dt.Rows.Count - 1]["ToHub"] = gvRow.Cells[16].Text;
dt.AcceptChanges();
}
return dt;
}
private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
{
DataRow[] dr = dt.Select("DocketNo = '" + gvRow.Cells[1].Text + "'");
if (dr.Length > 0)
{
dt.Rows.Remove(dr[0]);
dt.AcceptChanges();
}
return dt;
}
protected void CheckBox_CheckChanged(object sender, EventArgs e)
{
GetData();
SetData();
BindSecondaryGrid();
}
private void BindSecondaryGrid()
{
DataTable dt = (DataTable)ViewState["SelectedRecords"];
gvSelected.DataSource = dt;
gvSelected.DataBind();
}
}
I want to put the value of txtVehicleNo, which is outside the GridView gvSelected, into the bounded textbox field 'txtVehicleNo1' in all the rows of column VehicleNo of the GridView gvSelected.
Related
i am stuck in a situation where i need to add pagination to parent gridview only(I have a nested gridview where i don't want to add paginatiion to child gridview).i have searched for many example but however I couldn't find any solution.Please help me with this. I am stuck on this issue and could not find any workaround.i am getting input string was not in correct format error on rowcommand event on line
int id = int.Parse(e.CommandName.ToString());
<asp:GridView ID="GVLeader" runat="server" AutoGenerateColumns="false"
DataKeyNames="id" OnRowCommand="GVLeader_RowCommand"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "15" AllowSorting="true"
AllowPaging="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#
Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" >
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#
Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" runat="server" Text='<%#
Eval("Name") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Detail View" ControlStyle-
BackColor="#EBEBEB">
<ItemTemplate>
<asp:Button runat="server" ID="btnplus" Text="Edit Details"
CssClass="greenButton" CommandName='<%#Eval("id") %>'
CommandArgument='<%#Container.DataItemIndex%>' />
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "10" AllowSorting="true"
AllowPaging="true">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#
Eval("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Salary" >
<ItemTemplate>
<asp:Label ID="lblEmpSalary" runat="server" Text='<%#
Eval("EmpSalary") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpSalary" runat="server" Text='<%#
Eval("EmpSalary") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Address " >
<ItemTemplate>
<asp:Label ID="lblEmpAddress" runat="server" Text='<%#
Eval("Emp Address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmpAddress" runat="server" Text='<%#
Eval("Emp Address") %>' Width="100"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind Code:-
namespace Final
{
public partial class test : System.Web.UI.Page
{
SqlConnection con = new
SqlConnection(ConfigurationSettings.AppSettings["server"].ToString());
SqlConnection con1 = new SqlConnection("confidential"); //Create
sqlconnection
SqlDataAdapter da;
DataTable dt2, dt1;
Properties objlog = new Properties();
DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadGVLeader();
}
}
protected void GVLeader_RowCommand(object sender,
GridViewCommandEventArgs e)
{
int id = int.Parse(e.CommandName.ToString());
int rowindex = int.Parse(e.CommandArgument.ToString());
GridView GVMember =
(GridView)GVLeader.Rows[rowindex].FindControl("GVMember");
Button btn =
((Button)GVLeader.Rows[rowindex].FindControl("btnplus"));
if (btn.Text == "Edit Details")
{
btn.Text = "Cancel";
GVMember.DataSource = LoadGVMember(id);
GVMember.DataBind();
GVMember.Visible = true;
}
else
{
btn.Text = "Edit Details";
GVMember.Visible = false;
}
}
public void LoadGVLeader()
{
da = new SqlDataAdapter("select * from emptable", con);
dt = new DataTable();
da.Fill(dt);
GVLeader.DataSource = dt;
GVLeader.DataBind();
}
protected DataTable LoadGVMember(int id)
{
da = new SqlDataAdapter("select * from emptable where ID=" + id,
con);
dt1 = new DataTable();
da.Fill(dt1);
ViewState["dt"] = dt1;
return dt1;
}
protected void GVMember_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
Gv.EditIndex = e.NewEditIndex;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void GVMember_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
Gv.EditIndex = -1;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void GVMember_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
int id =
int.Parse(GVLeader.DataKeys[gvrow.RowIndex].Value.ToString());
int id1 = int.Parse(Gv.DataKeys[e.RowIndex].Value.ToString());
Gv.EditIndex = -1;
Gv.DataSource = LoadGVMember(id);
Gv.DataBind();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridView Gv = (GridView)sender;
GridViewRow gvrow = (GridViewRow)Gv.Parent.Parent;
Label lbldeleteid = (Label)gvrow.FindControl("lblID");
con.Open();
SqlCommand cmd = new SqlCommand("delete FROM emptable where ID='" +
Convert.ToInt32(GVLeader.DataKeys[e.RowIndex].Value.ToString()) + "'",
con);
cmd.ExecuteNonQuery();
con.Close();
LoadGVLeader();
}
}
}
remove pagination props from child grid(GVMember)
change
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-
CssClass="alt" PageSize = "10" AllowSorting="true"
AllowPaging="true">
with
<asp:GridView ID="GVMember" AutoGenerateColumns="false"
runat="server" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true"
DataKeyNames="id"
OnRowCancelingEdit="GVMember_RowCancelingEdit"
OnRowEditing="GVMember_RowEditing" OnRowDeleting="OnRowDeleting"
OnRowUpdating="GVMember_RowUpdating"
CssClass="mGrid" AlternatingRowStyle-
CssClass="alt" AllowSorting="true">
Im beginner for the ASP.NET ,Im develop the File Upload in Grid View with Ajax Modal Popup its working i can upload image and i can see uploaded image in uploaded folder, but i cant make uploaded image Path to grid view, can you please help me.
ASPX
<asp:UpdatePanel ID="UpdatePanelArt" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="table-responsive col-sm-12">
<asp:GridView ID="gvArticle" ShowHeaderWhenEmpty="True" ClientIDMode="AutoID" CssClass="table table-bordered table-condensed table-hover" AutoGenerateColumns="False" runat="server" AllowPaging="True" PageSize="15" OnRowDataBound="gvArticle_RowDataBound" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" OnRowUpdating="gvArticle_RowUpdating">
<%--<HeaderStyle BackColor="#3d4247" ForeColor="White" />--%>
<Columns>
<asp:TemplateField HeaderText="intArticleDetail" Visible="false">
<ItemTemplate>
<asp:Label ID="lblArticleDetailId" Width="2" Text='<%# Bind("intArticleDetailId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SectionID" Visible="false">
<ItemTemplate>
<asp:Label ID="lblSectionId" Width="2" Text='<%# Bind("intSectionId") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Section">
<ItemTemplate>
<asp:Label ID="lblSectionName" Width="100" Text='<%# Bind("strSectionName") %>' ClientIDMode="Static" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Compound">
<EditItemTemplate>
<asp:Label ID="lblItemTypeEdit" Width="50" Text='<%# Bind("strCompoundName") %>' lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCompoundId" Width="200" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemTemplate>
<asp:TextBox ID="txtdecSectionWeighte" Width="100%" Text='<%# Bind("decSectionWeight") %>' lientIDMode="Static" runat="server"> </asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:TemplateField HeaderText="Messagers">
<ItemTemplate>
<asp:TextBox ID="txtMessage" Width="100%" Text='<%# Bind("intMessageId") %>' ClientIDMode="Static" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Messagers">
<EditItemTemplate>
<asp:Label ID="lblMessageId" Width="50" Text='<%# Bind("strMessage") %>' ClientIDMode="Static" AutoPostBack="true" runat="server">
</asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlMessage" Width="300" CssClass="form-control my-DropDownThin" lientIDMode="Static" AutoPostBack="true" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<ItemTemplate>
<asp:Label ID="FilePath" Width="2" runat="server"></asp:Label>
</ItemTemplate>
<asp:TemplateField HeaderText="Images">
<ItemTemplate>
<%-- <asp:Image ID="Image1" ImageUrl='<%# Eval("StrImage") %>' runat="server" Height="100" />--%>
<%-- <asp:FileUpload runat="server" AutoPostBack="True" ID="uploadFImage" CommandArgument='<%# Eval("strImage") %>' ClientIDMode="Static"/>--%>
<asp:LinkButton ID="lnkUpload" runat="server" Text="Upload Resume" ></asp:LinkButton>
<%--Using ModalPopupExtender--%>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="lnkUpload"
PopupControlID="pnlUpload" BackgroundCssClass="ModalPopupBG" CancelControlID="btnCancel">
</asp:ModalPopupExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:Image ImageUrl="~/Uploaded Images/Default.png" runat="server" ID="btnViewFImage" Width="40" Height="40"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F7F7F7" />
<SortedAscendingHeaderStyle BackColor="#4B4B4B" />
<SortedDescendingCellStyle BackColor="#E5E5E5" />
<SortedDescendingHeaderStyle BackColor="#242121" />
</asp:GridView>
</div>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="gvArticle"/>
</Triggers>
</asp:UpdatePanel>
</div>
</div><asp:Panel ID="pnlUpload" runat="server" Width="450px" BackColor="#E39A19"
BorderColor="#C3680D" BorderStyle="Solid">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<table style="width: 450px; margin: 0 auto">
<tr>
<td align="right" style="background-image: url('backTable.PNG')">
</td>
</tr>
<tr>
<td align="left">
<asp:FileUpload ID="flp_Resume" runat="server" Width="222px" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator8" runat="server"
ControlToValidate="flp_Resume" ErrorMessage="*"
ToolTip="Please Select a File to Upload."></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator5" runat="server"
ControlToValidate="flp_Resume" ErrorMessage="*"
ToolTip="Only txt,doc or docx files are Allowed"
ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+((.pdf)|(.doc)|(.txt)|(.docx))$"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td align="left">
<asp:Button ID="btnUpload" runat="server" Text="Upload" Width="80px"
onclick="btnUpload_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" Width="80px" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblError" runat="server" Font-Bold="True" Font-Names="Georgia"
ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnUpload"/>
</Triggers>
cs
#region Detail Save1
private DataTable CreateDetailSave()
{
DataTable dtDetailSave1 = new DataTable();
DataColumn dc1;
dc1 = new DataColumn("intArticleDetailId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intSectionId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intCompoundId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("decSectionWeight");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("intMessageId");
dtDetailSave1.Columns.Add(dc1);
dc1 = new DataColumn("uploadFImage");
dtDetailSave1.Columns.Add(dc1);
foreach (GridViewRow row in gvArticle.Rows)
{
DataRow dr = dtDetailSave1.NewRow();
Label lblintArticleDetailId = (Label)row.FindControl("lblArticleDetailId");
Label lblSectionId = (Label)row.FindControl("lblSectionId");
DropDownList ddlCompound = (DropDownList)row.FindControl("ddlCompoundId");
TextBox txtdecSectionWeighte = (TextBox)row.FindControl("txtdecSectionWeighte");
DropDownList intMessage = (DropDownList)row.FindControl("ddlMessage");
FileUpload uploadFImage = (FileUpload)row.FindControl("uploadFImage");
dr["intArticleDetailId"] = CurrentMode == "Add" ? -1 : Convert.ToInt32(lblintArticleDetailId.Text);
dr["intSectionId"] = Convert.ToInt32(lblSectionId.Text);
dr["intCompoundId"] = ddlCompound.SelectedValue;
dr["decSectionWeight"] = txtdecSectionWeighte.Text.Trim() != "" ? Convert.ToDecimal(txtdecSectionWeighte.Text.Trim()) : 0;
dr["intMessageId"] = intMessage.SelectedValue;
dr["uploadFImage"] = uploadFImage.HasFile;
dtDetailSave1.Rows.Add(dr);
}
return dtDetailSave1;
}
#endregion
#region Save
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
if (FSaveConfirmation() == true)
{
string strArticleNo;
int intStatus = 8;
if (CurrentMode == "Add")
{
strArticleNo = "aaaaaaaa";
}
else
{
strArticleNo = txtArticleNo.Text.ToString();
}
DataTable dtDetailSave1 = CreateDetailSave();
string PageName = Path.GetFileNameWithoutExtension(Page.AppRelativeVirtualPath);
string Saved = clsArticle.saveArticleData(SelectedArticleId, strArticleNo, txtArticleDescription.Text.ToString(), txtRemarks.Text.ToString(), intStatus, 1, CurrentMode,
PageName, 16, dtDetailSave1);
if (Saved != "Error")
{
lblMsg.ForeColor = System.Drawing.Color.Green;
if (CurrentMode == "Add")
{
lblMsg.Text = "Record Saved Successfully";
txtArticleNo.Text = Saved.ToString();
}
else if (CurrentMode == "Modify")
{
lblMsg.Text = "Record Updated Successfully";
}
else if (CurrentMode == "Delete")
{
lblMsg.Text = "Record Deleted Successfully";
}
else if (CurrentMode == "Confirm")
{
lblMsg.Text = "Record Confirmed Successfully";
}
btnClear.Enabled = true;
btnSave.Enabled = true;
}
else if (Saved == "Error")
{
lblMsg.Text = "Article Saving Error";
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Save Confirmation
private bool FSaveConfirmation()
{
lblMsg.ForeColor = System.Drawing.Color.Red;
Boolean blnSaveCon = true;
//if (CurrentMode == "Add")
//{
if (txtArticleDescription.Text.ToString() == "")
{
lblMsg.Text = "Enter Article Description";
blnSaveCon = false;
goto end;
}
//}
end: { }
return blnSaveCon;
}
#endregion
#region Get controls in page
private void GetControlList<T>(ControlCollection controlCollection, List<T> resultCollection) where T : Control
{
foreach (Control control in controlCollection)
{
if (control is T)
resultCollection.Add((T)control);
if (control.HasControls())
GetControlList(control.Controls, resultCollection);
}
}
#endregion
#region pageload
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ClearControls();
FillArticleDetails();
EnableControls(false);
Session["SearchPopup"] = false;
}
else
{
if (Session["SearchPopup"] != null)
{
SearchPopup = (bool)(Session["SearchPopup"]);
if (SearchPopup != false)
{
MyMPE.Show();
}
else
{
MyMPE.Hide();
}
}
vAdSearchParaList = new List<SearchParametors>();
}
}
#endregion
#region Advance Search
protected void btnAdSearchClose(object sender, ImageClickEventArgs e)
{
Session["SearchPopup"] = false;
Session["sSearchddlList"] = null;
GridView dtgResult = (GridView)ucDesignation.FindControl("ucgrdSearchConditions");
dtgResult.DataSource = null;
dtgResult.DataBind();
dtgAdSearchResult.DataSource = null;
dtgAdSearchResult.DataBind();
MyMPE.Hide();
}
#region Create Article table
private void createArticleDataTable()
{
if (dt.Columns.Count == 0)
{
dt.Columns.Add(new DataColumn("intArticleDetailId", typeof(int)));
dt.Columns.Add(new DataColumn("intSectionId", typeof(int)));
dt.Columns.Add(new DataColumn("strSectionName", typeof(string)));
dt.Columns.Add(new DataColumn("intCompoundId", typeof(string)));
dt.Columns.Add(new DataColumn("decSectionWeight", typeof(string)));
dt.Columns.Add(new DataColumn("intMessageId", typeof(string)));
dt.Columns.Add(new DataColumn("uploadFImage", typeof(string)));
}
gvArticle.DataSource = dt;
gvArticle.DataBind();
}
#endregion
#region Compound Grid - Add empty row
private void ArticleGridAddEmptyRow(int newId)
{
DataRow newDr = null;
newDr = dt.NewRow();
newDr["intArticleDetailId"] = 1;
newDr["intSectionId"] = 1;
newDr["strSectionName"] = "";
newDr["intCompoundId"] = "";
newDr["decSectionWeight"] = "";
newDr["intMessageId"] = "";
newDr["strImage"] = "";
dt.Rows.Add(newDr);
if (dtArticleDetails == null || dtArticleDetails.Rows.Count == 0)
{
dtArticleDetails = dt;
}
else
{
dtArticleDetails.Merge(dt);
gvArticle.DataSource = dt;
gvArticle.DataBind();
}
}
#endregion
private void FillArticleDetails()
{
DataSet dtCompoundData = clsArticle.GeArticleDetailData(SelectedArticleId);
if (dtCompoundData.Tables[0].Rows.Count > 0)
{
createArticleDataTable();
dt = dtCompoundData.Tables[0];
dtArticleDetails = dt;
gvArticle.DataSource = dtArticleDetails;
gvArticle.DataBind();
}
else
{
lblMsg.Text = "No Records Found";
}
}
protected void gvArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
}
else if (e.Row.RowType == DataControlRowType.DataRow)
{
{
}
DataTable CompoundCode = clsArticle.CompoundDataForGrid("");
DropDownList ddlCompoundId = (DropDownList)e.Row.FindControl("ddlCompoundId");
if (ddlCompoundId != null)
{
ddlCompoundId.DataTextField = "Compound Code";
ddlCompoundId.DataValueField = "Compound Id";
ddlCompoundId.DataSource = CompoundCode;
ddlCompoundId.DataBind();
string country = (e.Row.FindControl("ddlCompoundId") as DropDownList).Text;
ddlCompoundId.Items.FindByValue(country).Selected = true;
}
DataTable MsgCode = clsArticle.MessageDataForGrid("");
DropDownList ddlMessage = (DropDownList)e.Row.FindControl("ddlMessage");
if (ddlMessage != null)
{
ddlMessage.DataTextField = "Message Name";
ddlMessage.DataValueField = "Message Id";
ddlMessage.DataSource = MsgCode;
ddlMessage.DataBind();
ddlMessage.Items.Insert(0, new ListItem("Please select"));
string country = (e.Row.FindControl("ddlMessage") as DropDownList).Text;
ddlMessage.Items.FindByValue(country).Selected = true;
}
//}
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
if (flp_Resume.HasFile)
{
string fileName = Path.GetFileName(flp_Resume.PostedFile.FileName);
string fullpath = Path.GetFullPath(flp_Resume.PostedFile.FileName);
flp_Resume.PostedFile.SaveAs(Server.MapPath("~/Uploaded Images/") + fileName);
Response.Redirect(Request.Url.AbsoluteUri);
}
else
{
lblError.Text = "Please Select a File";
return;
}
}
I have a nested gridiview inside a repeater :
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SDSRepeaterCity" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<table>
<tr>
<td ><label style="color:black; font-size:20px;"><%#Eval("nome_citta") %></label></td>
<td style="display:none;"><asp:Label ID="lblIdCity" runat="server" Text='<%#Eval("id_citta") %>' ></asp:Label></td>
</tr>
<tr>
<td colspan="2">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="False"
CssClass="Grid"
EmptyDataText="Nessun risultato corrispondono alla sua ricerca"
ShowHeaderWhenEmpty="True" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt = "" style="cursor: pointer" src="../../../Images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="TipoServizio" HeaderText="TipoServizio" />
<asp:BoundField ItemStyle-Width="33%" DataField="Tipologia" HeaderText="Tipologia" />
<asp:TemplateField>
<HeaderTemplate>Prezzo di base</HeaderTemplate>
<ItemTemplate >
<asp:TextBox ID="TBPrezzo" style="text-align:center;font-size:14px;" runat="server" Text=""></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
<HeaderStyle Width="150px" />
</asp:TemplateField>
<asp:BoundField DataField="tipo_macchina" ItemStyle-CssClass="hide" HeaderStyle-CssClass="hide" HeaderText="AutoMezzo">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="tipo_macchina" HeaderText="AutoMezzo">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblGvIdCity" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
And a button update with the following code:
TraifRegBLL trigis = TraifRegBLL.Instance;
string strConnString1 = "connexion";
using (SqlConnection con = new SqlConnection(strConnString1))
{
using (SqlCommand cmd = new SqlCommand())
{
String id_aff = Session["id_affiliato"].ToString();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM TarifSMReg WHERE id_affiliato= #Codice ";
cmd.Parameters.AddWithValue("#Codice", id_aff);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
//Add new inseriment
for (int i = 0; i < Repeater1.Items.Count; i++)
{
GridView gvCustomers = Repeater1.Items[i].FindControl("gvCustomers") as GridView;
for (int j = 0; j < gvCustomers.Rows.Count; j++)
{
Label lblGvIdCity = gvCustomers.Rows[j].FindControl("lblGvIdCity") as Label;
GridView gvOrders = gvCustomers.Rows[j].FindControl("gvOrders") as GridView;
for (int k = 0; k < gvOrders.Rows.Count; k++)
{
TextBox TBPrezzo = gvOrders.Rows[k].FindControl("TBPrezzo") as TextBox;
if (String.IsNullOrEmpty(TBPrezzo.Text)==true) { TBPrezzo.Text = "0"; }
if (Convert.ToDouble(TBPrezzo.Text) > 0)
{
TarifSMReg t = new TarifSMReg();
t.id_citta = lblGvIdCity.Text;
t.id_affiliato = Session["id_affiliato"].ToString();
t.tipologia_macchina = gvCustomers.Rows[j].Cells[2].Text;
t.TipoServizio = gvOrders.Rows[k].Cells[0].Text;
t.Tipologia = gvOrders.Rows[k].Cells[1].Text;
t.PrezzoBaseRG = Convert.ToDouble(TBPrezzo.Text.Replace(",", "."));
trigis.addTarifReg(t);
}
}
}
}
here is the result if i insert the price the first time:
but if i update the price will be duplicated like
this.
Can anyone explain me why?
thank you
I am using ObjectDataSource to Bind and update the grid .It is working fine and the records are updating in the database but after updating ,it is still showing the same records in the grid (Previous Values). Please help me that what i will do so that after database updation, The grid will display updated records ,not the old records.Please modify my code also in case if any one found the solution.
Thanks in Advance.
Please find the code below.
GridView Code:-
<asp:Panel ID="pnlGrdShift" runat="server" ScrollBars="Auto" Width="900px" Height="520px" CssClass="srcColor">
<cc1:GridView ID="gvShift" runat="server" AutoGenerateColumns="False" AllowSorting="True"
CssClass="grid"
OnDataBound="gvShift_DataBound"
DataSourceID="odsShiftDetails"
AllowPaging="True"
ShowFooter="false"
onrowcancelingedit="gvShift_RowCancelingEdit"
onrowcommand="gvShift_RowCommand"
onrowdeleting="gvShift_RowDeleting"
onrowediting="gvShift_RowEditing"
onrowupdating="gvShift_RowUpdating"
OnSelectedIndexChanged="gvShift_SelectedIndexChanged"
OnRowDataBound="gvShift_RowDataBound">
<AlternatingRowStyle CssClass="altrowstyle" />
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle" Wrap="false" />
<EmptyDataRowStyle BackColor="#edf5ff" Height="300px" VerticalAlign="Middle" HorizontalAlign="Center" />
<EmptyDataTemplate >
No Records Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="E Code" SortExpression="userecode" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserECode" runat="server" Text='<%#Eval("userecode") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserECode" runat="server" Text='<%#Eval("userecode") %>' style="width:50px;" CssClass="GridContent" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Name" SortExpression="username" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserName" runat="server" Text='<%#Eval("username") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserName" runat="server" Text='<%#Eval("username") %>' style="width:100px;" CssClass="GridContent"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift Start Time" SortExpression="ShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftStartTime" runat="server" ControlToValidate="ddlShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift End Time" SortExpression="ShiftEndTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftEndTime" runat="server" ControlToValidate="ddlShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="ShiftEndTIme" HeaderText="Shift End Time" SortExpression="ShiftEndTIme"/>--%>
<asp:TemplateField HeaderText="Saturday Shift Start Time" SortExpression="WeekendShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftStartTime" runat="server" ControlToValidate="ddlWeekendShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Saturday Shift End Time" SortExpression="weekendshiftendtime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftEndTime" runat="server" ControlToValidate="ddlWeekendShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update" ForeColor="White"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" ForeColor="White"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" ForeColor="White"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate >
<table width="100%" >
<tr>
<td style="text-align: left">
Page Size:
<asp:DropDownList ID="ddPageSize" runat="server" EnableViewState="true" OnSelectedIndexChanged="ddPageSize_SelectedIndexChanged" AutoPostBack="true" style="width:50px;">
<asp:ListItem Text="10" ></asp:ListItem>
<asp:ListItem Text="20" ></asp:ListItem>
<asp:ListItem Text="30" ></asp:ListItem>
<asp:ListItem Text="40" ></asp:ListItem>
<asp:ListItem Text="50" ></asp:ListItem>
</asp:DropDownList>
</td>
<td style="text-align: right">
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
</td>
</tr>
</table>
</PagerTemplate>
</cc1:GridView>
</asp:Panel>
<asp:ObjectDataSource ID="odsShiftDetails" runat="server"
SelectMethod="GetShiftInfoSortedPage" TypeName="EQ.DAL.ShiftInfoDB"
EnablePaging="True" SelectCountMethod="GetShiftInfoCount"
SortParameterName="sortExpression" UpdateMethod="UpdateShift">
<UpdateParameters>
<asp:Parameter Name="sql"/>
</UpdateParameters>
<SelectParameters>
<asp:ControlParameter ControlID="hfSearchCriteria" Name="searchCriteria" Direction="Input" />
</SelectParameters>
</asp:ObjectDataSource>
Code Behind for Update:-
protected void gvShift_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftStartTime");
TextBox txtShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftEndTime");
TextBox txtWeekendShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftStartTime");
TextBox txtWeekendShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftEndTime");
Label lblUserecode = (Label)gvShift.Rows[e.RowIndex].FindControl("lblEditUserECode");
string userecode = lblUserecode.Text.ToString();
string _ShiftStart = txtShiftStartTime.Text.ToString();
string _ShiftEnd = txtShiftEndTime.Text.ToString();
string _WeekendShiftStart = txtWeekendShiftStartTime.Text.ToString();
string _WeekendShiftend = txtWeekendShiftEndTime.Text.ToString();
EmployeeQuotientCL.Entities.ConfigurationVariables _configVariables = new ConfigurationVariables();
string databaseConnectionString = _configVariables.ConnectionString;
SqlConnection sqlConnection = null;
if (((databaseConnectionString + string.Empty) != string.Empty))
{
DBConnect dbConnect = new DBConnect(_configVariables.ConnectionString);
sqlConnection = dbConnect.SQLConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
string sql=null;
cmd.CommandText = "UPDATE UserInfo SET ShiftStartTime ='" + _ShiftStart + "',ShiftEndTime='" + _ShiftEnd.ToString() + "',Weekendshiftstarttime='" + _WeekendShiftStart.ToString() + "',Weekendshiftendtime='" + _WeekendShiftend.ToString() + "' WHERE UserECode=" + userecode.ToString();
odsShiftDetails.UpdateParameters["sql"].DefaultValue = cmd.CommandText;
odsShiftDetails.Update();
}
}
catch (Exception ex)
{
}
}
ShiftInfoDBCache.cs
public class ShiftInfoDB
{
private const string SHIFTINFO_CACHE_KEY = "SHIFTINFO_DATA";
private const string SHIFTINFOCOUNT_CACHE_KEY = "SHIFTINFO_COUNT";
static EmployeeQuotientCL.Entities.ConfigurationVariables _config = new EmployeeQuotientCL.Entities.ConfigurationVariables();
static int _SupervisorecodeforShift;
public static DataTable GetShiftInfoSortedPage(int maximumRows, int startRowIndex, string sortExpression, string searchCriteria)
{
_SupervisorecodeforShift=EmployeeQuotientCL.Entities.StaticGlobalValue.UserId;
if (string.IsNullOrEmpty(sortExpression))
sortExpression = "userecode";
try
{
if (ShiftInfoDBCache.isRecordsCached(SHIFTINFO_CACHE_KEY))
return ShiftInfoDBCache.GetData(SHIFTINFO_CACHE_KEY, startRowIndex + 1, maximumRows, sortExpression, searchCriteria);
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
string sql = "select distinct MP.userecode,UI.username,UI.ShiftStartTime,UI.ShiftEndTime,UI.WeekendShiftStartTime,UI.weekendshiftendtime from AssociateSupervisorMapping MP inner join UserInfo UI on MP.Userecode=UI.Userecode where supervisorecode=" + _SupervisorecodeforShift.ToString();
SqlCommand custCommand = new SqlCommand(sql, dbConnection);
custCommand.CommandType = CommandType.Text;
SqlDataAdapter ad = new SqlDataAdapter(custCommand);
DataTable dtCustomers = new DataTable();
ad.Fill(dtCustomers);
dbConnection.Close();
//Cache records
ShiftInfoDBCache.Add(SHIFTINFO_CACHE_KEY, dtCustomers);
}
catch (Exception e)
{
throw;
}
return ShiftInfoDBCache.GetData(SHIFTINFO_CACHE_KEY, startRowIndex + 1, maximumRows, sortExpression, null);
}
public static int GetShiftInfoCount(string searchCriteria)
{
_SupervisorecodeforShift=EmployeeQuotientCL.Entities.StaticGlobalValue.UserId;
int custCount = 0;
try
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
string sql = "select Count(*)from (select distinct MP.userecode,UI.username,UI.ShiftStartTime,UI.ShiftEndTime,UI.WeekendShiftStartTime,UI.weekendshiftendtime from AssociateSupervisorMapping MP inner join UserInfo UI on MP.Userecode=UI.Userecode where supervisorecode="+_SupervisorecodeforShift.ToString()+")AS internalQuery";
if (!string.IsNullOrEmpty(searchCriteria))
sql = sql + " where " + searchCriteria;
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.Connection = dbConnection;
dbConnection.Open();
sqlCommand.CommandType = CommandType.Text;
custCount = Convert.ToInt32(sqlCommand.ExecuteScalar());
dbConnection.Close();
if (ShiftInfoDBCache.Get(SHIFTINFOCOUNT_CACHE_KEY) != null)
{
// remove customers data if customers count has changed since first cache
if (Convert.ToInt32(ShiftInfoDBCache.Get(SHIFTINFOCOUNT_CACHE_KEY)) != custCount && string.IsNullOrEmpty(searchCriteria))
{
ShiftInfoDBCache.Remove(SHIFTINFO_CACHE_KEY);
}
}
if (string.IsNullOrEmpty(searchCriteria))
ShiftInfoDBCache.Add(SHIFTINFOCOUNT_CACHE_KEY, custCount);
}
catch (Exception e)
{
throw;
}
return custCount;
}
public static void UpdateShift(string sql)
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.CommandType=CommandType.Text;
sqlCommand.CommandText=sql;
dbConnection.Open();
sqlCommand.Connection = dbConnection;
//sqlCommand.CommandType = CommandType.Text;
sqlCommand.ExecuteNonQuery();
dbConnection.Close();
}
}
ShiftInfoDBCache.cs
public class ShiftInfoDBCache
{
public static bool isRecordsCached(string cacheKey)
{
Cache dbCache = HttpContext.Current.Cache;
if (dbCache[cacheKey] == null)
return false;
return true;
}
public static void Add(string key, object value)
{
Cache dbCache = HttpContext.Current.Cache;
dbCache.Add(key, value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
public static object Get(string key)
{
Cache dbCache = HttpContext.Current.Cache;
return dbCache[key];
}
public static object Remove(string key)
{
Cache dbCache = HttpContext.Current.Cache;
return dbCache.Remove(key);
}
public static DataTable GetData(string cacheKey, int startRowIndex, int maximumRowNumber, string sortExpression, string searchCriteria)
{
Cache dbCache = HttpContext.Current.Cache;
if (dbCache[cacheKey] != null)
{
DataTable dtble = dbCache[cacheKey] as DataTable;
DataTable dtblNew = dtble.Clone();
DataRow[] rows = dtble.Select(searchCriteria, sortExpression);
if (rows != null)
{
if (rows.Count() > 0)
{
if (startRowIndex > rows.Count())
{
startRowIndex = rows.Count() - maximumRowNumber;
if (startRowIndex < 0)
{
startRowIndex = 1;
maximumRowNumber = rows.Count();
}
}
for (int i = startRowIndex - 1; i < (startRowIndex + maximumRowNumber - 1); i++)
{
if (i < rows.Count())
dtblNew.ImportRow(rows[i]);
}
return dtblNew;
}
}
return dtblNew;
}
return null;
}
}
public static void UpdateShift(string sql)
{
SqlConnection dbConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ToString());
SqlCommand sqlCommand = new SqlCommand(sql, dbConnection);
sqlCommand.CommandType=CommandType.Text;
sqlCommand.CommandText=sql;
dbConnection.Open();
sqlCommand.Connection = dbConnection;
//sqlCommand.CommandType = CommandType.Text;
sqlCommand.ExecuteNonQuery();
dbConnection.Close();
ShiftInfoDBCache.Remove(SHIFTINFO_CACHE_KEY);
}
Modifying UpdateShift Method in ShiftInfoDB.cs fixed my issue.
The sorting works fine when u fill the gridview using SQL datasource in the aspx page...
but now i am using template field and the columns are filled separately in the codebehind and the sorting is not working...
my code is
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False"
ondatabound="GridView1_DataBound"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="File Name" ItemStyle-Width="40%" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Failure Count" ItemStyle-Width="10%" >
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server"></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
</Columns></GridView>
and my codebehind is:
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection();
connection.ConnectionString = ConfigurationManager.ConnectionStrings["SumooHAgentDBConnectionString"].ConnectionString;
connection.Open();
SqlCommand sqlCmd = new SqlCommand("SELECT FileName,FailureCount from Files where MachineID=#strID , connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlCmd.Parameters.AddWithValue("strID", strID);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
string nameoffiles = dt.Rows[i]["FileName"].ToString();
buFailureCode.Add(code);
string count = dt.Rows[i]["BuFailureCount"].ToString();
buFailureCount.Add(count);
}
}
connection.Close();
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
if (namesOfFiles.Count != 0)
{
for (int i = 0; i < namesOfFiles.Count; i++)
{
GridViewRow myRow = GridView1.Rows[i];
Label Label1 = (Label)myRow.FindControl("Label1");
Label Label3 = (Label)myRow.FindControl("Label3");
Label1.Text = namesOfFiles[i].ToString();
Label3.Text = buFailureCount[i].ToString();
}}}
set SortExpression
I think you'll have to handle the OnSorting event and do the actual sorting yourself in code-behind. The API documentation has an example.