I have a gridview having a textbox and a checkbox.when the checkbox is checked,a value will be populated into the textbox which a user may alter the value.
Here is the code for the gridview
<asp:GridView ID="gvPayment" runat ="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="Vertical" Width="100%" ShowFooter="true" CssClass="jumbSize1" OnRowDataBound="gvPayment_RowDataBound" AllowPaging="true" PageSize="5" OnPageIndexChanging="gvPayment_PageIndexChanging" >
<Columns>
<asp:TemplateField HeaderStyle-Width="5%">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" CssClass="checkbox" OnCheckedChanged="chkSelect_CheckedChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TRANSACTION DATE" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="SalesDate" runat="server" Text='<%#Eval("Date", "{0:dd/MM/yyyy}") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Submit" Text="Submit" runat="server" OnClick="Submit_Click" CssClass="btn btn-primary" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sales Code" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="SalesCode" runat="server" Text='<%#Eval("SALES_CODE") %>' />
</ItemTemplate>
<FooterTemplate>
<div style="padding: 0 0 5px 0;">
<asp:Label Text="Page Totals" runat="server" align="right" />
</div>
<div>
<asp:Label Text="Grand Totals" runat="server" align="right" />
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ACTUAL SALE" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="ActualSales" runat="server" Text='<%#Eval("ACTUAL", "{0:N2}") %>' />
</ItemTemplate>
<FooterTemplate>
<div style="padding: 0 0 5px 0;">
<asp:Label ID="PageActual" runat="server" align="right" />
</div>
<div>
<asp:Label ID="GrandActual" runat="server" align="right" />
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ADVANCE" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="AdvPay" runat="server" Text='<%#Eval("ADVANCE", "{0:N2}") %>' />
</ItemTemplate>
<FooterTemplate>
<div style="padding: 0 0 5px 0;">
<asp:Label ID="PageAdvance" runat="server" align="left" />
</div>
<div>
<asp:Label ID="GrandAdvance" runat="server" align="left" />
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AMOUNT DUE" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="AmtDue" runat="server" Text='<%#Eval("DUE", "{0:N2}") %>' />
</ItemTemplate>
<FooterTemplate>
<div style="padding: 0 0 5px 0;">
<asp:Label ID="PageDue" runat="server" align="left" />
</div>
<div>
<asp:Label ID="GrandDue" runat="server" align="left" />
</div>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AMOUNT PAID" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:TextBox ID="AmtPaid" runat="server" CssClass="form-control CapLock" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#4870BE" ForeColor="#FFFFFF" />
<FooterStyle BackColor="#76543c" ForeColor="#FFFFFF" Font-Bold="true" />
<HeaderStyle BackColor="#76543c" ForeColor="#FFFFFF" Font-Bold="true" />
<PagerSettings Mode="NextPrevious" NextPageText="Next >>" PreviousPageText="Prev <<" />
<PagerStyle BackColor="#76543c" ForeColor="#FFFFFF" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" /></asp:Gridview>
Here is the code to bind gridview to data source and get the grand totals in viewstate
private void GetCustomer()
{
dt = new DataTable();
try
{
using (con = new SqlConnection(conString))
{
using (cmd = con.CreateCommand())
{
string query = #"dbo.sp_get_sales";
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("#ID", CustInfo.SelectedValue);
con.Open();
da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
//CALCULATE THE TOTAL AMOUNTS AND HOLD THE VALUE IN A "VIEWSTATE"
ViewState["TotalActual"] = null;
if (ViewState["TotalActual"] == null)
{
Decimal dActual = 0;
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
dActual += dt.Rows[i].Field<Decimal>("ACTUAL");
}
ViewState["TotalActual"] = dActual.ToString("N2");
}
ViewState["TotalAdvance"] = null;
if (ViewState["TotalAdvance"] == null)
{
Decimal dAdvance = 0;
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
dAdvance += dt.Rows[i].Field<Decimal>("ADVANCE");
}
ViewState["TotalAdvance"] = dAdvance.ToString("N2");
}
ViewState["TotalDue"] = null;
if (ViewState["TotalDue"] == null)
{
Decimal dDue = 0;
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
dDue += dt.Rows[i].Field<Decimal>("DUE");
}
ViewState["TotalDue"] = dDue.ToString("N2");
}
}
//BIND QUERY RESULT WITH THE GRIDVIEW
gvPayment.DataSource = dt;
gvPayment.DataBind();
}
}
catch (Exception ex)
{
ErrorMessage.Text = "An error occured: " + ex.Message;
}
finally
{
con.Close();
con.Dispose();
}
foreach (GridViewRow row in gvPayment.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
TextBox AmtPaid = (TextBox)row.FindControl("AmtPaid");
AmtPaid.Attributes.Add("readonly", "readonly");
}
}
}
Here is the code to enable and populate textbox on check changed event
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
GridViewRow row = ((GridViewRow)((CheckBox)sender).NamingContainer);
int index = row.RowIndex;
CheckBox chkSelect = (CheckBox)gvPayment.Rows[index].FindControl("chkSelect");
TextBox AmtPaid = (TextBox)gvPayment.Rows[index].FindControl("AmtPaid");
Label AmtDue = (Label)gvPayment.Rows[index].FindControl("AmtDue");
if (chkSelect.Checked && chkSelect != null)
{
AmtPaid.Text = AmtDue.Text.Replace(",", "");
AmtPaid.Attributes.Remove("readonly");
}
else
{
AmtPaid.Text = string.Empty;
AmtPaid.Attributes.Add("readonly", "readonly");
}
}
The textbox get populated with the desired value when the checkbox is selected but both controls lost their values on pageindexchanging event.
I want the checkbox to maintain its state and textbox to maintain whatever value user entered when the pageindexchanging event is called.
Here is the code to move to next page
protected void gvPayment_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvPayment.PageIndex = e.NewPageIndex;
GetCustomer();
}
Note: I have gone through all suggested similar questions with no luck or success.
You have to persist them, for example by storing a Disctionary<int, bool> in the ViewState where the key is the RowIndex and the value is the bool(CheckBox is Checked?):
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["EnabledAmtPaidTextBoxes"] = new Dictionary<int, bool>();
GetCustomer();
}
}
I would encapsulate this logic in a method, you need to call it from RowDataBound and CheckedChanged. You don't need that final loop in GetCustomer anymore:
protected void gvPayment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
EnabledAmtPaidTextBox(e.Row);
}
}
protected void chkSelect_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkSelect = (CheckBox)sender;
GridViewRow row = (GridViewRow)chkSelect.NamingContainer;
EnabledAmtPaidTextBox(row, chkSelect.Checked);
}
private void EnabledAmtPaidTextBox(GridViewRow row, bool? newCheckedOrApplyOld = null)
{
TextBox AmtPaid = (TextBox)row.FindControl("AmtPaid");
Label AmtDue = (Label)row.FindControl("AmtDue");
CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
Dictionary<int, bool> enabledAmtPaidTextBoxes = (Dictionary<int, bool>)ViewState["EnabledAmtPaidTextBoxes"];
if (!enabledAmtPaidTextBoxes.ContainsKey(row.RowIndex))
enabledAmtPaidTextBoxes[row.RowIndex] = false;
if (newCheckedOrApplyOld.HasValue)
enabledAmtPaidTextBoxes[row.RowIndex] = newCheckedOrApplyOld.Value;
else
chkSelect.Checked = enabledAmtPaidTextBoxes[row.RowIndex];
if (enabledAmtPaidTextBoxes[row.RowIndex])
{
AmtPaid.Text = AmtDue.Text.Replace(",", "");
AmtPaid.Attributes.Remove("readonly");
}
else
{
AmtPaid.Text = string.Empty;
AmtPaid.Attributes.Add("readonly", "readonly");
}
}
Also, if you use the using-statement you don't need con.Close and con.Dispose in finally because that is done by the using-statement already.
Hi I have used gridview to create a table.
Is there a way to implement edit and delete.
I have done it in PHP before. The method I would like to use is create two more columns in the table with edit and delete buttons on each row. Then when the buttons are click it passes the 'id' through the URL and able to edit or delete. Not really sure how to do this in asp.net webforms. Below is my code for the table. Thank you.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
<asp:BoundField HeaderText="PatientID" DataField="patientID" />
<asp:BoundField HeaderText="Location" DataField="location" />
</Columns>
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
The GridView supports those operations. You can add a CommandField which will contain the command buttons or LinkButtons (you can choose the type of button and assign the text of each button). The patientID field should be included in the DataKeyNames property of the GridView, in order to retrieve it when the time comes to update or delete the record in the database.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="patientID"
OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowUpdating="GridView1_RowUpdating" OnRowDeleting="GridView1_RowDeleting" >
<Columns>
<asp:CommandField ShowEditButton="true" ShowCancelButton="true" ShowDeleteButton="true" />
<asp:BoundField HeaderText="Surgery" DataField="surgery" />
...
</Columns>
You will then need to handle a few events in code-behind:
// The RowEditing event is called when data editing has been requested by the user
// The EditIndex property should be set to the row index to enter edit mode
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
// The RowCancelingEdit event is called when editing is canceled by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
// The RowUpdating event is called when the Update command is selected by the user
// The EditIndex property should be set to -1 to exit edit mode
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
string surgery = (string)e.NewValues["surgery"];
string location = (string)e.NewValues["location"];
// Update here the database record for the selected patientID
GridView1.EditIndex = -1;
BindData();
}
// The RowDeleting event is called when the Delete command is selected by the user
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int patientID = (int)e.Keys["patientID"]
// Delete here the database record for the selected patientID
BindData();
}
Since the data must be bound to the GridView at the end of each of those event handlers, you can do it in a BindData utility function, which should also be called when the page loads initially:
private void BindData()
{
SqlCommand cmd = new SqlCommand("select surgery, patientID, location from details", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
And Store Procedure is:
USE [DemoProjet]
GO
/****** Object: StoredProcedure [dbo].[Customers_CRUD] Script Date: 11-Jan-17 2:57:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[Customers_CRUD]
#Action VARCHAR(10)
,#BId INT = NULL
,#Username VARCHAR(50) = NULL
,#Provincename VARCHAR(50) = NULL
,#Cityname VARCHAR(50) = NULL
,#Number VARCHAR(50) = NULL
,#Name VARCHAR(50) = NULL
,#ContentType VARCHAR(50) = NULL
,#Data VARBINARY(MAX) = NULL
AS
BEGIN
SET NOCOUNT ON;
--SELECT
IF #Action = 'SELECT'
BEGIN
SELECT BId , Username,Provincename,Cityname,Number,Name,ContentType, Data
FROM tblbooking
END
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO tblbooking(Username,Provincename,Cityname,Number,Name,ContentType, Data)
VALUES (#Username ,#Provincename ,#Cityname ,#Number ,#Name ,#ContentType ,#Data)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE tblbooking
SET Username = #Username,Provincename = #Provincename,Cityname = #Cityname,Number = #Number,Name = #Name,ContentType = #ContentType,Data = #Data
WHERE BId = #BId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM tblbooking
WHERE BId = #BId
END
END
GO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
namespace FinalYearProject
{
public partial class MBooking : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.Parameters.AddWithValue("#Action", "SELECT");
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void Insert(object sender, EventArgs e)
{
string Username = txtUsername.Text;
string Provincename = txtProvinceName.Text;
string Cityname = txtCityname.Text;
string Number = txtNumber.Text;
string Name = txtName.Text;
string ContentType = txtContentType.Text;
string Data = txtData.Text;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "INSERT");
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Provincename ", Provincename);
cmd.Parameters.AddWithValue("#Cityname", Cityname);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#ContentType", ContentType);
//cmd.Parameters.AddWithValue("#Data", Data);
cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string Username = (row.FindControl("txtUserName") as TextBox).Text;
string Provincename = (row.FindControl("txtProvincename") as TextBox).Text;
string Cityname = (row.FindControl("txtCityname") as TextBox).Text;
string Number = (row.FindControl("txtNumber") as TextBox).Text;
string Name = (row.FindControl("txtName") as TextBox).Text;
string ContentType = (row.FindControl("txtContentType") as TextBox).Text;
string Data = (row.FindControl("txtData") as TextBox).Text;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "UPDATE");
cmd.Parameters.AddWithValue("#BId", BId);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Provincename ", Provincename);
cmd.Parameters.AddWithValue("#Cityname", Cityname);
cmd.Parameters.AddWithValue("#Number", Number);
cmd.Parameters.AddWithValue("#Name", Name);
cmd.Parameters.AddWithValue("#ContentType",ContentType) ;
cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary).Value = new Byte[] { 0xDE, 0xAD, 0xBE, 0xEF };
//cmd.Parameters.AddWithValue("#ContentType", SqlDbType.VarBinary, -1);
//cmd.Parameters.AddWithValue("#Data", SqlDbType.VarBinary, -1);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1;
this.BindGrid();
}
protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.BindGrid();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
//if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != GridView1.EditIndex)
//{
// (e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
//}
}
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Name, Data, ContentType from tblbooking where BId=#BId";
cmd.Parameters.AddWithValue("#BId",id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
protected void OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
int BId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string constr = ConfigurationManager.ConnectionStrings["cmt"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "DELETE");
cmd.Parameters.AddWithValue("#BId", BId);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
this.BindGrid();
}
}
}
And Aspx page is:
<%# Page Title="" Language="C#" MasterPageFile="~/admin.Master" AutoEventWireup="true" CodeBehind="MBooking.aspx.cs" Inherits="FinalYearProject.MBooking" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<style type="text/css">
<%-- body
{
font-family: Arial;
font-size: 10pt;
}
table
{
border: 1px solid #ccc;
border-collapse: collapse;
background-color: #fff;
}
table th
{
background-color: #B8DBFD;
color: #333;
font-weight: bold;
}
table th, table td
{ background-color: #B8DBFD;
padding: 5px;
border: 1px solid #ccc;
}
table, table table td
{
border: 3px solid #ccc;
}
--%>
.style1
{
width: 184px;
}
</style>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True"
OnPageIndexChanging="OnPageIndexChanging" PageSize="6" DataKeyNames="BId"
OnRowDataBound="OnRowDataBound" OnRowEditing="OnRowEditing" OnRowCancelingEdit="OnRowCancelingEdit"
OnRowUpdating="OnRowUpdating" OnRowDeleting="OnRowDeleting"
EmptyDataText="No records has been added."
Style="margin:20px 0px 0px 25px;" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="4" Height="250px"
Width="1035px" >
<Columns>
<asp:TemplateField HeaderText="Username" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%# Eval("Username") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUsername" style = "Width:100px;" runat="server" Text='<%# Eval("Username") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProvinceName" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblProvinceName" runat="server" Text='<%# Eval("Provincename") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtProvinceName" style = "Width:100px;" runat="server" Text='<%# Eval("Provincename") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField HeaderText="CityName" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblCityname" runat="server" Text='<%# Eval("Cityname") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCityname" style = "Width:100px;" runat="server" Text='<%# Eval("Cityname") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Number" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblNumber" runat="server" Text='<%# Eval("Number") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNumber" style = "Width:100px;" runat="server" Text='<%# Eval("Number") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Name" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtName" style = "Width:100px;" runat="server" Text='<%# Eval("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="ContentType" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblContentType" runat="server" Text='<%# Eval("ContentType") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtContentType" style = "Width:100px;" runat="server" Text='<%# Eval("ContentType") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField><asp:TemplateField HeaderText="Data" ItemStyle-Width="120">
<ItemTemplate>
<asp:Label ID="lblData" runat="server" Text='<%# Eval("Data") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtData" style = "Width:100px;" runat="server" Text='<%# Eval("Data") %>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width="120px"></ItemStyle>
</asp:TemplateField>
<asp:TemplateField> <ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="Download" OnClick="DownloadFile"
CommandArgument='<%# Eval("BId") %>'></asp:LinkButton>
</ItemTemplate></asp:TemplateField>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowDeleteButton="true"
ItemStyle-Width="100" >
<ItemStyle Width="100px"></ItemStyle>
</asp:CommandField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Center"
Font-Bold="True" Font-Italic="True" Font-Underline="True" Width="20px" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
<br />
<table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse; margin:10px 0px 0px 25px;">
<tr>
<td style="width: 100px; background-color:#003399; color:#CCCCFF;">
<b> Username:</b><br />
<asp:TextBox ID="txtUsername" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Provincename:</b><br />
<asp:TextBox ID="txtProvinceName" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b>Cityname:</b><br />
<asp:TextBox ID="txtCityname" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Number:</b><br />
<asp:TextBox ID="txtNumber" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> Name:</b><br />
<asp:TextBox ID="txtName" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b> ContentType:</b><br />
<asp:TextBox ID="txtContentType" runat="server" Width="120" />
</td>
<td style="width: 100px;background-color:#003399; color:#CCCCFF;">
<b>Data:</b><br />
<asp:TextBox ID="txtData" runat="server" Width="120" />
</td>
<td style="background-color:#003399; color:#CCCCFF;" class="style1">
<asp:Button ID="btnAdd" runat="server" CssClass="btn btn-info" Text="Add"
OnClick="Insert" Width="187px" />
</td>
</tr>
</table>
</asp:Content>
This is my first time for using ASP.NET to develop website.
I want to show my data from database in a GridView with Paging function and I can implement it by using OnPageIndexChanging="GridView1_PageIndexChanging" but I want to use my own pager so the question is
"How can I link my pager (the right bottom in the pic) to the gridview instead the pager which generated by the ASP.NET"
Pics:
This is my code in aspx
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-condensed table-striped table-primary table-vertical-center"
PageSize="3" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="UNIT_ID" HeaderText="รหัส" SortExpression="unitid">
<HeaderStyle CssClass="center" />
<ItemStyle Width="10%" CssClass="center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code in cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
protected void bindGridView() {
string sqltxt = "select * from drug_units"; //where UNIT_ID =:unitid";
CommandData comm = new CommandData();
comm.SetCommandText(sqltxt);
//comm.AddInputParameter("unitid", "5");
List<DrugsUnit> dy = new List<DrugsUnit>();
comm.ExecuteNonQuery();
dy = comm.ExecuteToList<DrugsUnit>();
GridView1.DataSource = dy;
/*BoundField boundField = new BoundField();
boundField.DataField = "UNIT_ID";
boundField.HeaderText = "ID";
boundField.SortExpression = "ID";
boundField.HeaderStyle.CssClass = "center";
boundField.ItemStyle.CssClass = "center";
GridView1.Columns.Add(boundField);*/
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
upGridPager.Update();
e.Row.SetRenderMethodDelegate(new RenderMethod((w, r) =>
{
e.Row.SetRenderMethodDelegate(null);
using (var ms = new StringWriter())
using (var writer = new HtmlTextWriter(ms))
{
e.Row.RenderControl(writer);
GridPager.InnerHtml = "<table>" + ms.ToString() + "</table>";
}
}));
}
The aspx could look like this (outside of your grid)
<asp:UpdatePanel ID="upGridPager" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div runat="server" id="GridPager" />
</ContentTemplate>
</asp:UpdatePanel>
I have a GridView that has a column named Run Time and it uses TextBoxes rTime. I'm going to be bewing this GridView on an andriod operating system and want it to pull a keypad if someone clicks on the textbox. This has worked before without the GridView, but I've been getting a The name 'rTime' does not exist in the current context error. Here is my aspx code: `
<asp:TemplateField HeaderText="labelID" Visible="false">
<ItemTemplate>
<asp:Label ID="ID" runat="server" Text='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="labelfirstname" Visible="true" runat="server" Text='<%# Eval("fName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="labellastname" Visible="true" runat="server" Text='<%# Eval("lName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Run Time Needed">
<ItemTemplate>
<asp:Label ID="labelrTimeN" Visible="true" runat="server" Text='<%# Eval("rTimeN") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Run Time">
<ItemTemplate>
<div style="display:none"><asp:TextBox ID="rTime" runat="server" Height="16px"
ontextchanged="TextBox1_TextChanged" Width="108px"></asp:TextBox></div>
<span class="style4"><strong>Meter Run:</strong></span><span class="style5"> </span><input onblur="document.getElementById('<%=rTime.ClientID %>').value = this.value"
type="tel" style="width: 100px; height: 31px;" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>`
Here is c#:
private bool isEditMode = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
UpdatePanel1.Visible = false;
}
private void BindData()
{
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=TestDB;Persist Security Info=True;User ID=v2soft;Password=passwordv2soft";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT Id, fName, lName, rTimeN, rTime FROM bleaTest", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
isEditMode = true;
UpdatePanel1.Visible = true;
BindData();
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
Update();
}
protected bool IsInEditMode
{
get { return this.isEditMode; }
set { this.isEditMode = value; }
}
private void Update()
{
StringBuilder sb = new StringBuilder();
foreach (GridViewRow row in GridView1.Rows)
{
sb.Append("UPDATE bleaTest SET rTime = '");
sb.Append((row.FindControl("rTime") as TextBox).Text);
sb.Append("'");
sb.Append(" WHERE id = ");
sb.Append(Convert.ToInt32((row.FindControl("ID") as Label).Text));
sb.Append(" ");
}
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=TestDB;Persist Security Info=True;User ID=v2soft;Password=passwordv2soft";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlCommand myCommand = new SqlCommand(sb.ToString(), myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
isEditMode = false;
BindData();
UpdatePanel1.Visible = false;
}
protected void gvUsers_RowDataBound(object sender, GridViewCommandEventArgs e)
{
}
Thank you in advance!!
Did some more research and re-wrote the code a little. Here's the update:
<asp:TemplateField HeaderText="Run Time">
<ItemTemplate>
<div style="display:none"> <asp:TextBox ID="rTime" runat="server" type="number" Text='<%# Eval("rTime") %>' ></asp:TextBox></div>
<input onblur="document.getElementById('<%# ((GridViewRow)Container).FindControl("rTime").ClientID %>').value = this.value"
type="tel" style="width: 100px; height: 31px;" />
</ItemTemplate>
<asp:Panel ID="pnlFocusAreaPanel" runat="server" GroupingText="Focus Area" Width="800">
<table cellspacing="0" cellpadding="0" width="750">
<tr>
<td>
<asp:GridView ID="dgFocusAreaDetails" runat="server" Width="100%" CssClass="dgStyle"
AutoGenerateColumns="False" BorderColor="Silver" BorderWidth="1px" CellPadding="0"
ShowHeader="False" OnSelectedIndexChanged="dgFocusAreaDetails_SelectedIndexChanged"
DataKeyNames="PK_ID">
<FooterStyle Font-Underline="True" HorizontalAlign="Center" VerticalAlign="Middle">
</FooterStyle>
<Columns>
<asp:TemplateField HeaderText="Focus Area" HeaderStyle-BackColor="Silver">
<ItemStyle Width="90%" />
<ItemTemplate>
<asp:Label runat="server" ID="lblFocusArea" Text='<%# DataBinder.Eval(Container.DataItem, "FOCUS_AREA_NAME").ToString()%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Current Valid" HeaderStyle-BackColor="Silver">
<ItemStyle Width="10%" HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="chkFocusArea" runat="server" OnCheckedChanged="OnCheckChangedEvent"
AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td align="left">
<asp:TextBox ID="txtFocusArea" runat="server" Width="300px" CausesValidation="true" CssClass="txtStyle" ValidationGroup="focusArea">
</asp:TextBox>
<cc1:TextBoxWatermarkExtender ID="txtFocusAreaWaterMark" runat="server" TargetControlID="txtFocusArea"
WatermarkText="Add Focus Area" WatermarkCssClass="WaterMarkStyle">
</cc1:TextBoxWatermarkExtender>
<asp:Button ID="btnAddFocusArea" runat="server" Text="AddFocusArea" CssClass="btnStyle"
OnClick="btnAddFocusArea_Click" CausesValidation="true" ValidationGroup="focusArea" />
<asp:RequiredFieldValidator ID="reqtxtFocusArea" runat="server" ControlToValidate="txtFocusArea"
ErrorMessage="Please enter focus area" Display="Dynamic" ValidationGroup="focusArea">
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexFocusArea" runat="server" ErrorMessage="Invalid characters(<,>,#)"
ControlToValidate="txtFocusArea" ValidationExpression="^([^<#>]*)$" ValidationGroup="focusArea"
Display="Dynamic" SetFocusOnError="true">
</asp:RegularExpressionValidator>
</td>
</tr>
</table>
</asp:Panel>
and in code behind
protected void btnAddFocusArea_Click(object sender, EventArgs e)
{
string strFocusArea = txtFocusArea.Text;
OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
if (strFocusArea == string.Empty || strFocusArea == txtFocusAreaWaterMark.WatermarkText)
{
lblError.Text = "Focus area is not entered";
}
else
{
string insertQuery = "INSERT INTO LK_CODECAT_FOCUS_AREA(FOCUS_AREA_NAME,FK_ADDED_BY,ADDED_ON) "+
" VALUES('" + strFocusArea + "', "+Session["UserID"] +", GETDATE())";
try
{
myConnection.Open();
OleDbCommand myCommandToInsert = new OleDbCommand(insertQuery, myConnection);
myCommandToInsert.ExecuteNonQuery();
}
catch(Exception exc)
{
ExceptionLogger.LogException(exc);
}
finally
{
if (myConnection != null)
{
myConnection.Close();
}
}
PopulateFocusArea();
}
txtFocusArea.Text = txtFocusAreaWaterMark.WatermarkText;
}
private void PopulateFocusArea()
{
OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings["SQLConnectionString"]);
string selectQuery = "SELECT PK_ID, FOCUS_AREA_NAME, IS_CURRENT_FOCUS FROM LK_CODECAT_FOCUS_AREA LKCFA ORDER BY FOCUS_AREA_NAME";
if (Session["RoleID"].ToString() == "1" || ((Session["WorkID"].ToString() != "9") ||
(Session["WorkID2"].ToString() != "9") ||
(Session["WorkID3"].ToString() != "9")))
{
try
{
myConnection.Open();
OleDbCommand myCommandFocusArea = new OleDbCommand(selectQuery, myConnection);
OleDbDataAdapter myAdapter = new OleDbDataAdapter(myCommandFocusArea);
DataSet ds = new DataSet();
myAdapter.Fill(ds);
dgFocusAreaDetails.DataSource = ds;
dgFocusAreaDetails.ShowHeader = true;
dgFocusAreaDetails.DataBind();
}
catch (Exception exc)
{
ExceptionLogger.LogException(exc);
}
finally
{
if (myConnection != null)
{
myConnection.Close();
}
}
}
}
protected void dgFocusAreaDetails_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedCategory = dgFocusAreaDetails.SelectedRow.Cells[1].Text;
int index = dgFocusAreaDetails.SelectedIndex;
lblError.Text = dgFocusAreaDetails.DataKeys[index].Value.ToString();
}
public void OnCheckChangedEvent(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
string chkfocusarea = ((Control)chk).ID;
//string focusAreaDetails = dgFocusAreaDetails.SelectedRow.Cells[0].Text;
int index =Convert.ToInt32(dgFocusAreaDetails.SelectedIndex);
if (chk.Checked)
{
string updateQuery = "UPDATE [LK_CODECAT_FOCUS_AREA] SET [IS_CURRENT_FOCUS] = 1 WHERE PK_ID = "
+Convert.ToInt32( dgFocusAreaDetails.DataKeys[index].Value)+" ";
}
else
{
lblError.Text = "unchecked";
}
}
i want to know how i find the datakeyvalue on checked event because updateQuery in checked event is generating exception.
Could you add a asp:button instead of using the checkbox on your GridView and fire an OnRowUpdating event?
Alternatively you could store the index value in a session varaible to pick up on your chkbox click.
edit: found this post is that any help?
They suggest you have to check each row to see if the value has changed.