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;
}
}
Related
I am working in a ASP.NET project in an empty web application in C# and I have made a gridview with CRUD operations. But when I execute my project and click on the buttons I have made it takes me to the first row and I then have to scroll back down again. It is really annoying but I do not know why it does that. Even though I have used MaintainScrollPositionOnPostBack="true" it does not work. Is there anything I cad add to my code or something I have to be aware of?
Default.aspx
<%# Page Language="C#" MaintainScrollPositionOnPostBack="true" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestUsers.Default" %>
<link href="TestUsers.css" rel="stylesheet" type="text/css" />
<!DOCTYPE html>
<link rel="stylesheet" href="TestUsers.css">
<link rel="shortcut icon" type="image/x-icon" href="~/orbitone.ico" />
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ESDTESTERS</title>
<%-- <meta http-equiv="refresh" content="20">--%>
</head>
<body>
<form id="form1" runat="server">
<div>
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<br /><br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Sing Out" />
<br /><br />
<asp:TextBox ID="TextBox1" runat="server" Width="200px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Search" Width="100px" />
<br />
</div>
<asp:GridView ID="gvTestUsers" runat="server" AutoGenerateColumns="False" ShowFooter="True" DataKeyNames="tbl_users_key" ShowHeaderWhenEmpty="True" OnRowCommand="gvTestUsers_RowCommand" OnRowEditing="gvTestUsers_RowEditing" OnRowCancelingEdit="gvTestUsers_RowCancelingEdit"
OnRowDeleting="gvTestUsers_RowDeleting" OnRowUpdating="gvTestUsers_RowUpdating" HorizontalAlign="Center" OnPageIndexChanging="gvTestUsers_PageIndexChanged"
BackColor="#CCCCCC" BorderColor="#000000" BorderStyle="Solid" BorderWidth="3px" CellPadding="5" Width="1300px" CellSpacing="2" ForeColor="Black" PageSize="15" AllowPaging="True" >
<%--Theme Properties--%>
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" Font-Size="Large" ForeColor="White" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#808080" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#383838" />
<Columns>
<asp:TemplateField HeaderText="tbl_users_key">
<ItemTemplate>
<asp:Label Text='<%# Eval("tbl_users_key") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtID" Text='<%# Eval("tbl_users_key") %>' runat="server" ReadOnly="true" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label Text='<%# Eval("Name") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" ReadOnly="True" Text='<%# Eval("Name") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNamefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CostCenter">
<ItemTemplate>
<asp:Label Text='<%# Eval("CostCenter") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCostCenter" ReadOnly="True" Text='<%# Eval("CostCenter") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCostCenterfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee">
<ItemTemplate>
<asp:Label Text='<%# Eval("Employee") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployee" ReadOnly="True" Text='<%# Eval("Employee") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmployeefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FootPlate">
<ItemTemplate>
<asp:Label Text='<%# Eval("FootPlate") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFootPlate" Text='<%# Eval("FootPlate") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFootPlatefooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="WirstCord">
<ItemTemplate>
<asp:Label Text='<%# Eval("WirstCord") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtWirstCord" Text='<%# Eval("WirstCord") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtWirstCordfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Excluded">
<ItemTemplate>
<asp:Label Text='<%# Eval("Excluded") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExcluded" Text='<%# Eval("Excluded") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtExcludedfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment">
<ItemTemplate>
<asp:Label Text='<%# Eval("Comment") %>' runat="server" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtComment" Text='<%# Eval("Comment") %>' runat="server" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCommentfooter" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/delete.png" runat="server" CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete this record?');" ToolTip="Delete" Width="20px" Height="20px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/GridImages/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/GridImages/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/GridImages/add.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<asp:Label ID="lblSuccessMessage" Text="" runat="server" ForeColor="Green" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
<br />
<asp:Label ID="lblErrorMessage" Text="" runat="server" ForeColor="Red" style="text-align:center" Font-Bold="true" Font-Size="x-Large" />
</div>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace TestUsers
{
public partial class Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGridView();
}
}
void PopulateGridView()
{
DataTable dtbl = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
sqlCon.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("Select * FROM TBL_USERS", sqlCon);
sqlDa.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
}
else
{
dtbl.Rows.Add(dtbl.NewRow());
gvTestUsers.DataSource = dtbl;
gvTestUsers.DataBind();
gvTestUsers.Rows[0].Cells.Clear();
gvTestUsers.Rows[0].Cells.Add(new TableCell());
gvTestUsers.Rows[0].Cells[0].ColumnSpan = dtbl.Columns.Count;
gvTestUsers.Rows[0].Cells[0].Text = "No Data Found.";
gvTestUsers.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
protected void gvTestUsers_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName.Equals("AddNew"))
{
int tbl_users_key = 0;
TextBox myTxt;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtNamefooter"));
string Name;
Name = myTxt.Text;
string CostCenter;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCostCenterfooter"));
CostCenter = myTxt.Text;
string Employee;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtEmployeefooter"));
Employee = myTxt.Text;
Boolean FootPlate;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtFootPlatefooter"));
FootPlate = Convert.ToBoolean(myTxt.Text);
Boolean WirstCord;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtWirstCordfooter"));
WirstCord = Convert.ToBoolean(myTxt.Text);
Boolean Excluded;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtExcludedfooter"));
Excluded = Convert.ToBoolean(myTxt.Text);
string Comment;
myTxt = ((TextBox)gvTestUsers.FooterRow.FindControl("txtCommentfooter"));
Comment = myTxt.Text;
string sMsg;
sMsg = "";
bool btest = fcEditTBL_USERS(tbl_users_key, Name, CostCenter, Employee, FootPlate, WirstCord, Excluded, Comment, ref sMsg,0);
if (btest == false)
{
lblErrorMessage.Text = sMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = Name + " Was Added To Record.";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_RowEditing(object sender, GridViewEditEventArgs e)
{
gvTestUsers.EditIndex = e.NewEditIndex;
PopulateGridView();
}
protected void gvTestUsers_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gvTestUsers.EditIndex = -1;
PopulateGridView();
}
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, Convert.ToBoolean(dltFootPlate), Convert.ToBoolean(dltWirstCord), Convert.ToBoolean(dltExcluded), dltComment,ref dltsMsg,2);
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
gvTestUsers.EditIndex = -1;
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
public bool fcEditTBL_USERS
(int tbl_users_key, string Name, string CostCenter, string Employee, bool FootPlate, bool WirstCord, bool Excluded, string Comment, ref string sMsg, int iMode)
{
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(connectionString))
try
{
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("spEditTBL_USERS", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnParameter = sqlCmd.Parameters.Add(new SqlParameter("#RETURN_VALUE", DbType.Int32));
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add("#ID", SqlDbType.Int).Value=tbl_users_key ;
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value=Name;
sqlCmd.Parameters.Add("#CostCenter", SqlDbType.VarChar, 10).Value=CostCenter;
sqlCmd.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value=Employee;
sqlCmd.Parameters.Add("#FootPlate", SqlDbType.Bit).Value=FootPlate;
sqlCmd.Parameters.Add("#WirstCord", SqlDbType.Bit).Value=WirstCord;
sqlCmd.Parameters.Add("#Excluded", SqlDbType.Bit).Value=Excluded;
sqlCmd.Parameters.Add("#Comment", SqlDbType.VarChar, 255).Value=Comment;
sqlCmd.Parameters.Add("#MODE", SqlDbType.SmallInt).Value =iMode;
sqlCmd.Parameters.Add("#MSG", SqlDbType.NVarChar, 255).Value=sMsg;
sqlCmd.Parameters["#MSG"].Direction = ParameterDirection.Output;
sqlCmd.ExecuteNonQuery();
sMsg = sqlCmd.Parameters["#MSG"].Value.ToString();
int rtn = (int)sqlCmd.Parameters["#RETURN_VALUE"].Value;
if (rtn != 0)
{
return false;
}
sqlCmd.Dispose();
return true;
}
finally
{
}
}
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, Convert.ToBoolean(tmpFootPlate), Convert.ToBoolean(tmpWirstCord), Convert.ToBoolean(tmpExcluded), tmpComment,ref tmpsMsg,1);
//Reload Page
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
protected void gvTestUsers_PageIndexChanged(object sender, GridViewPageEventArgs e)
{
gvTestUsers.PageIndex = e.NewPageIndex;
PopulateGridView();
}
protected void Button1_Click(object sender, EventArgs e)
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand (find,con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
Response.Redirect("LoginForm.aspx");
}
}
}
Thank you for the explanation. Please try setting gridview editindex before populating the gridview (after updating and deleting ) Hope this helps.
Working below code for me.
protected void gvTestUsers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
//Parameters Set From Grid
string tmpUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string tmpName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string tmpCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string tmpEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string tmpFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string tmpWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string tmpExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string tmpComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string tmpsMsg = "";
//Call function for SP_UPDATE
bool FuncResult = fcEditTBL_USERS(Convert.ToInt32(tmpUsers_key), tmpName, tmpCostCenter, tmpEmployee, tmpFootPlate, tmpWirstCord, tmpExcluded, tmpComment, ref tmpsMsg, "Update");
//add this
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Updated.";
lblErrorMessage.Text = "";
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
And the row deleting below,
protected void gvTestUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
try
{
{
gvTestUsers.EditIndex = e.RowIndex;
PopulateGridView();
//Parameters for delete operation
string dltUsers_key = (gvTestUsers.Rows[e.RowIndex].FindControl("txtID") as TextBox).Text.Trim();
string dltName = (gvTestUsers.Rows[e.RowIndex].FindControl("txtName") as TextBox).Text.Trim();
string dltCostCenter = (gvTestUsers.Rows[e.RowIndex].FindControl("txtCostCenter") as TextBox).Text.Trim();
string dltEmployee = (gvTestUsers.Rows[e.RowIndex].FindControl("txtEmployee") as TextBox).Text.Trim();
string dltFootPlate = (gvTestUsers.Rows[e.RowIndex].FindControl("txtFootPlate") as TextBox).Text.Trim();
string dltWirstCord = (gvTestUsers.Rows[e.RowIndex].FindControl("txtWirstCord") as TextBox).Text.Trim();
string dltExcluded = (gvTestUsers.Rows[e.RowIndex].FindControl("txtExcluded") as TextBox).Text.Trim();
string dltComment = (gvTestUsers.Rows[e.RowIndex].FindControl("txtComment") as TextBox).Text.Trim();
string dltsMsg = "";
//Call function for SP_Delete
bool FuncDelete = fcEditTBL_USERS(Convert.ToInt32(dltUsers_key), dltName, dltCostCenter, dltEmployee, dltFootPlate, dltWirstCord,dltExcluded, dltComment, ref dltsMsg, "Delete");
if (FuncDelete == false)
{
lblErrorMessage.Text = dltsMsg;
lblSuccessMessage.Text = " ";
return;
}
gvTestUsers.EditIndex = -1;
PopulateGridView();
lblSuccessMessage.Text = "Selected Record Deleted.";
lblErrorMessage.Text = "";
}
}
catch (Exception ex)
{
lblSuccessMessage.Text = "";
lblErrorMessage.Text = ex.Message;
}
}
I solved it by moving the SearchBox-Event code into my PopulateGridView.
So now the PopulateGridView looks like this:
void PopulateGridView()
{
string find = "select * from TBL_USERS where (Name like '%' + #Name + '%') or (employee like '%' + #Employee + '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#Name", SqlDbType.VarChar, 255).Value = TextBox1.Text;
comm.Parameters.Add("#Employee", SqlDbType.VarChar, 32).Value = TextBox1.Text;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "Name");
da.Fill(ds, "Employee");
gvTestUsers.DataSource = ds;
gvTestUsers.DataBind();
con.Close();
}
And the Searchbox-Event:
protected void Button1_Click(object sender, EventArgs e)
{
PopulateGridView();
}
Else it would jump straight to Void PopulateGridView each time I would try to use an EDIT,CREATE or DELETE operation.
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 have created gridview with paging and search a data within gridview.I have number of data and number of page if u filter data in gridview it successfully display result with paging. After display i will click on next page because gridview will display only 10 records per page but i have more than 10 records which i have filtered so it will display page wise. Then when i click next page gridview will loads whole data from database and display but i want display only filtered record while searching data.
the aspx code is below
<asp:Button ID="Search" Text="Search" runat="server" CssClass="searchbtn" OnClick="Search_Click" />
<asp:GridView ID="gvEdit" runat="server" AutoGenerateColumns="False" DataKeyNames="slno" OnRowCreated="gvEdit_RowCreated" OnPageIndexChanging="gvEdit_PageIndexChanging" Width="100%" AllowPaging="True" PageSize="10" OnRowCommand="gvEdit_RowCommand">
<HeaderStyle HorizontalAlign="Center" BackColor="#2D96CE" ForeColor="White" />
<AlternatingRowStyle BackColor="#D4EFFD" />
<PagerSettings Position="Top" />
<PagerStyle Height="8px" HorizontalAlign="Center" />
<PagerTemplate>
<table align="center" style="width: 100%;" cellpadding="0" cellspacing="0" border="0">
<tr>
<td align="center" style="width: 60%;">
<table align="center" width="50%">
<tr>
<td>
<asp:ImageButton ToolTip="First Page" CommandName="Page" CommandArgument="First" runat="server" ID="ImgeBtnFirst" ImageUrl="../Images/First.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Previous Page" CommandName="Page" CommandArgument="Prev" runat="server" ID="ImgbtnPrevious" ImageUrl="../Images/Previous.jpg" />
</td>
<td style=" width: 8%;">
<asp:Label ID="lblpageindx" CssClass="labelBold" Text="Page : " runat="server"></asp:Label>
<asp:DropDownList ToolTip="Goto Page" ID="ddlPageSelector" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPageSelector_SelectedIndexChanged" CssClass="combo_common_nowidth hide">
</asp:DropDownList>
</td>
<td>
<asp:ImageButton ToolTip="Next Page" CommandName="Page" CommandArgument="Next" runat="server" ID="ImgbtnNext" ImageUrl="../Images/Next.jpg" />
</td>
<td>
<asp:ImageButton ToolTip="Last Page" CommandName="Page" CommandArgument="Last" runat="server" ID="ImgbtnLast" ImageUrl="../Images/Last.jpg" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</PagerTemplate>
<Columns>
<asp:BoundField DataField="form_key" HeaderText="FilingID" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="business_key" HeaderText="BusinessKey" HeaderStyle-CssClass="hide" ItemStyle-CssClass="hide" />
<asp:BoundField DataField="ref_no" HeaderText="Reference" HeaderStyle-Width="200px" />
<asp:BoundField DataField="fum" HeaderText="Period" HeaderStyle-Width="11%" />
<asp:BoundField DataField="filing_type" HeaderText="Filing Type" HeaderStyle-Width="19%" />
<asp:BoundField DataField="business_name" HeaderText="Business" HeaderStyle-Width="13%" />
<asp:BoundField DataField="filing_status" HeaderText="Status" HeaderStyle-Width="200px" />
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="View">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" OnClick="lnkBtnViewDetails_Click" Text='<%#Eval("form_details")%>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="" HeaderText="Schedule1" ItemStyle-Width="6.9%">
<ItemTemplate>
<a href="Schedule12290.aspx?key=<%#Eval("form_key") %>" target="_blank">
<img src="<%#Eval("schedule1") %>" alt="" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Copy">
<ItemTemplate>
<asp:ImageButton ID="lnkDuplicate" runat="server"
ImageUrl="~/Images/grid/file_duplicate 35x35.png" OnClick="lnkbtnDuplicate_Click" ToolTip="Edit" CssClass='<%#Eval("duplicate") %>' OnClientClick="javascript:return confirm('Are you sure you want to copy from previous years filing?');" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Edit">
<ItemTemplate>
<asp:ImageButton ID="lnkBtnContinue" runat="server"
ImageUrl="~/Images/grid/edit3.png" OnClick="imgBtnContinue_Click" ToolTip="Edit" CssClass='<%# Eval("continue")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="120px" HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgBtnDel" runat="server"
ImageUrl="~/Images/grid/delBlue.png" OnClick="imgBtnDelete_Click" ToolTip="Delete" CssClass='<%#Eval("delete") %>' OnClientClick="javascript:return confirm('Do you want to delete this file permanently?');" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and aspx.cs code is below
protected void Search_Click(object sender, EventArgs e)
{
this.BindGrid();
}
private void BindGrid()
{
try
{
if (txtsearch.Text != "")
{
if (ViewState["data"] != null)
{
DataTable dt = (DataTable)ViewState["data"];
DataView dv = new DataView(dt);
dv.RowFilter = "ref_no Like '%" + txtsearch.Text + "%' OR fum Like '%" + txtsearch.Text + "%' OR filing_type Like '%" + txtsearch.Text + "%'OR business_name Like '%" + txtsearch.Text + "%'OR filing_status Like '%" + txtsearch.Text + "%'";
ViewState["filter"] = dv;
gvEdit.DataSource = dv;
gvEdit.DataBind();
//gvformlist.DataSource = dv;
//gvformlist.DataBind();
}
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
protected void Reset_Click(object sender, EventArgs e)
{
txtsearch.Text = "";
gvEdit.DataSource = ViewState["data"];
gvEdit.DataBind();
//gvformlist.DataSource = ViewState["data"];
//gvformlist.DataBind();
}
protected void gvformlist_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
//gvEdit.PageIndex = e.NewPageIndex;
//gvformlist.PageIndex = e.NewPageIndex;
LoadFormList();
}
protected void gvformlist_RowDataBound(object sender, GridViewRowEventArgs e)
{
GridViewRow pagerRow = gvEdit.TopPagerRow;
Label pageLabel = (Label)pagerRow.Cells[0].FindControl("CurrentPageLabel");
if (e.Row.RowType == DataControlRowType.Pager)
{
pageLabel.Text = "Page " + (gvEdit.PageIndex + 1) + " of " + gvEdit.PageCount;
}
}
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
public void SetPagerButtonStates(GridView gridView, GridViewRow gvPagerRow, Page page, string DDlPager)
{
// to Get No of pages and Page Navigation
int pageIndex = gridView.PageIndex;
int pageCount = gridView.PageCount;
ImageButton btnFirst = (ImageButton)gvPagerRow.FindControl("ImgeBtnFirst");
ImageButton btnPrevious = (ImageButton)gvPagerRow.FindControl("ImgbtnPrevious");
ImageButton btnNext = (ImageButton)gvPagerRow.FindControl("ImgbtnNext");
ImageButton btnLast = (ImageButton)gvPagerRow.FindControl("ImgbtnLast");
btnFirst.Enabled = btnPrevious.Enabled = (pageIndex != 0);
btnNext.Enabled = btnLast.Enabled = (pageIndex < (pageCount - 1));
DropDownList ddlPageSelector = (DropDownList)gvPagerRow.FindControl(DDlPager);
ddlPageSelector.Items.Clear();
for (int i = 1; i <= gridView.PageCount; i++)
{
ddlPageSelector.Items.Add(i.ToString());
}
ddlPageSelector.SelectedIndex = pageIndex;
string strPgeIndx = Convert.ToString(gridView.PageIndex + 1) + " of "
+ gridView.PageCount.ToString();
Label lblpageindx = (Label)gvPagerRow.FindControl("lblpageindx");
lblpageindx.Text += strPgeIndx;
}
protected void ddlPageSelector_SelectedIndexChanged(object sender, EventArgs e)
{
gvEdit.PageIndex = ((DropDownList)sender).SelectedIndex;
LoadFormList();
}
protected void gvEdit_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
SetPagerButtonStates(gvEdit, e.Row, this, "ddlPageSelector");
}
}
protected void gvEdit_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
I have changed code in gvEdit_PageIndexChanging as per someone suggestion code is below
protected void gvEdit_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
if (ViewState["filter"] != null)
{
gvEdit.PageIndex = e.NewPageIndex;
gvEdit.DataSource = ViewState["filter"];
gvEdit.DataBind();
}
else
{
gvEdit.PageIndex = e.NewPageIndex;
LoadFormList();
}
}
catch (Exception ex)
{
string a = ex.Message;
}
}
after that i run the code and i am getting error
error is System.Runtime.Serialization.SerializationException: Type 'System.Data.DataView' in Assembly 'System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
According to your question I try to give an answer. If you find my answer useful then mark is as answer or vote it up.
What I have done in below code is when user click on search button without input any student name it shows per page 10 records of all students and if you search by name it shows only specific students with paging. In below code I use a stored procedure and in that I put three parameters such as following:
#startRowIndex int
#pageSize int
#studentname varchar(50) = NULL
Default.aspx markup:
<form id="form1" runat="server">
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<table>
<tr>
<td>Gridview Pagging</td>
</tr>
<tr>
<td>
<asp:TextBox ID="searchbox" runat="server"></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="btnSearch_Click" />
</td>
</tr>
</table>
<div>
<asp:GridView ID="gv" runat="server" Width="100%" EmptyDataText="No Data Found!"
ShowFooter="False" AutoGenerateColumns="False" SkinID="WithOutPaging" GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="Studentname" HeaderText="Student Names"></asp:BoundField>
<asp:BoundField DataField="Studentage" HeaderText="Age"></asp:BoundField>
</Columns>
<EmptyDataRowStyle CssClass="emptyrow" />
<HeaderStyle CssClass="headerstyle2" />
<FooterStyle CssClass="footerstyle"></FooterStyle>
<EditRowStyle CssClass="editrowstyle"></EditRowStyle>
<SelectedRowStyle CssClass="selectedrowstyle"></SelectedRowStyle>
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center"></PagerStyle>
</asp:GridView>
</div>
<div style="margin-top: 20px; margin-bottom: 70px;" align="center">
<asp:Button ID="btnFirst" runat="server" Text="First" CommandName="First" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnPrevious" runat="server" Text="Previous" CommandName="Previous"
OnCommand="ChangePage" Visible="False" />
<asp:Button ID="btnNext" runat="server" Text="Next" CommandName="Next" OnCommand="ChangePage"
Visible="False" />
<asp:Button ID="btnLast" runat="server" Text="Last" CommandName="Last" OnCommand="ChangePage"
Visible="False" />
<br />
<br />
<asp:Label ID="lblPageText1" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> Page </asp:Label>
<asp:Label ID="lblCurrentPage" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
<asp:Label ID="lblPageText2" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#3495D0"> of </asp:Label>
<asp:Label ID="lbltotalPages" runat="server" CssClass="label" Visible="False" BackColor="Transparent"
BorderColor="Transparent" ForeColor="#5c5c5c"></asp:Label>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
Default.aspx.cs code:
#region "Declaration"
private int pageSize = 10;
SqlConnection con;
string conquery = "Data Source=.;Initial Catalog=GridviewPagging;User ID=sa;Password = 123";
#endregion
#region "Events"
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["startRowIndex"] = 0;
ViewState["currentPageNumber"] = 0;
}
}
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "First":
ViewState["currentPageNumber"] = 1;
ViewState["startRowIndex"] = 0;
break;
case "Previous":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) - 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) - pageSize;
break;
case "Next":
ViewState["currentPageNumber"] = Int32.Parse(lblCurrentPage.Text) + 1;
ViewState["startRowIndex"] = Convert.ToInt32(ViewState["startRowIndex"]) + pageSize;
break;
case "Last":
ViewState["startRowIndex"] = pageSize * (Int32.Parse(lbltotalPages.Text) - 1);
ViewState["currentPageNumber"] = lbltotalPages.Text;
break;
}
this.fillgridview();
}
protected void btnSearch_Click(object sender, EventArgs e)
{
fillgridview();
}
#endregion
#region "Methods"
private DataSet ds(int RowIndex, int Pagesize, string studentname)
{
DataSet dataset;
try
{
con = new SqlConnection(conquery);
SqlCommand cmd = new SqlCommand("SP_GET_STUDENT_DATA", con);
cmd.Parameters.AddWithValue("#startRowIndex", RowIndex);
cmd.Parameters.AddWithValue("#pageSize", Pagesize);
cmd.Parameters.AddWithValue("#studentname", studentname);
cmd.CommandType = CommandType.StoredProcedure;
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
dataset = new DataSet();
da.Fill(dataset);
}
return dataset;
}
catch (SqlException ex)
{
return dataset = null;
}
}
private void fillgridview()
{
DataSet newds = ds(Convert.ToInt32(ViewState["startRowIndex"].ToString()), pageSize, searchbox.Text.Trim());
if (newds.Tables.Count == 0)
{
return;
}
else
{
btnFirst.Visible = true;
btnPrevious.Visible = true;
btnNext.Visible = true;
btnLast.Visible = true;
lblCurrentPage.Visible = true;
lbltotalPages.Visible = true;
lblPageText1.Visible = true;
lblPageText2.Visible = true;
ViewState["TotalRows"] = newds.Tables[1].Rows[0][0];
newds.Tables[1].Rows.Clear();
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 0)
{
ViewState["currentPageNumber"] = 1;
}
setPages();
this.gv.Visible = true;
this.gv.DataSource = newds.Tables[0];
this.gv.DataBind();
}
}
private void setPages()
{
lbltotalPages.Text = "";
lblCurrentPage.Text = "";
try
{
lbltotalPages.Text = CalculateTotalPages(Convert.ToDouble(ViewState["TotalRows"])).ToString();
lblCurrentPage.Text = (ViewState["currentPageNumber"] == null ? "0" : ViewState["currentPageNumber"].ToString());
if (Int32.Parse(lblCurrentPage.Text) == 0 | Int32.Parse(lbltotalPages.Text) == 0)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
else
{
if (Convert.ToInt32(ViewState["currentPageNumber"]) == 1)
{
this.btnPrevious.Enabled = false;
this.btnFirst.Enabled = false;
if (int.Parse(lbltotalPages.Text) > 0)
{
this.btnNext.Enabled = true;
this.btnLast.Enabled = true;
}
else
{
this.btnNext.Enabled = false;
this.btnLast.Enabled = false;
}
}
else
{
btnPrevious.Enabled = true;
btnFirst.Enabled = true;
}
if (Convert.ToInt32(ViewState["currentPageNumber"]) == int.Parse(lbltotalPages.Text))
{
btnNext.Enabled = false;
btnLast.Enabled = false;
}
else
{
btnNext.Enabled = true;
btnLast.Enabled = true;
}
}
}
catch (Exception ex)
{
}
}
private int CalculateTotalPages(double totalrows)
{
return Convert.ToInt32(Math.Ceiling(totalrows / pageSize));
}
#endregion
first set enablepagingandcallback = false in gridview , then add
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = SqlDataSource1; //it is the datasource with filtered query which does the work
GridView1.DataBind();
}
<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.
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.