I have a gridview and 2 buttons outside it. On button click all rows of gridview should become editable. I am using ITemplate class achive this task, but unable to complete it.
below is my code to get editable gridview:
public class GridViewTemplate : ITemplate
{
private DataControlRowType templateType;
private string columnName;
private string columnNameBinding;
private string controlType;
public GridViewTemplate(DataControlRowType type, string colname, string colNameBinding, string ctlType)
{
templateType = type;
columnName = colname;
columnNameBinding = colNameBinding;
controlType = ctlType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = columnName;
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
if (controlType == "Label")
{
Label lb = new Label();
lb.ID = "lblName";
lb.DataBinding += new EventHandler(this.OnDataBinding);
container.Controls.Add(lb);
}
else if (controlType == "TextBox")
{
TextBox tb = new TextBox();
tb.ID = "txtWeightage" + columnNameBinding;
tb.DataBinding += new EventHandler(this.OnDataBinding);
container.Controls.Add(tb);
}
default:
break;
}
}
public void OnDataBinding(object sender, EventArgs e)
{
object bound_value_obj = null;
Control ctrl = (Control)sender;
IDataItemContainer data_item_container = (IDataItemContainer)ctrl.NamingContainer;
bound_value_obj = DataBinder.Eval(data_item_container.DataItem, columnName);
switch (templateType)
{
case DataControlRowType.Header:
Label lb = (Label)sender;
lb.Text = bound_value_obj.ToString();
break;
case DataControlRowType.DataRow:
TextBox txtbox = (TextBox)sender;
txtbox.Text = bound_value_obj.ToString();
break;
}
}
}
It's one sample :
This post demonstrate how to make a GridView editable all the time using C# asp.net.
step1-: Create a table with name " items" with following columns("iterm_no","name","price")
where "iterm_no" is identity column.as describe below
create table items
(
iterm_no int identity(1,1),
name varchar(20),
price numeric(10,2)
)
step2- Now create a web page with name(EditableGridView). as describe below.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="EditableGridView.aspx.cs" Inherits="EditableGridView" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Editable GridView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="INTERM_NO" >
<FooterStyle BackColor="White" ForeColor="#000066" />
<Columns>
<asp:BoundField DataField="INTERM_NO" HeaderText="ITEM_N0" InsertVisible="False" ReadOnly="True"
SortExpression="INTERM_NO" />
<asp:TemplateField HeaderText="NAME" SortExpression="NAME">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NAME") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("INTERM_NO") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRICE" SortExpression="PRICE">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("PRICE") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
Text="Update" />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</form>
</body>
</html>
step 3- Go to your code behind (EditableGridView.cs) as describe below.
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class EditableGridView : System.Web.UI.Page
{
SqlConnection con;
bool[] rowChanged;
protected void Page_Load(object sender, EventArgs e)
{
string conString = ConfigurationSettings.AppSettings["mycon"];
con = new SqlConnection(conString);
int totalRows = GridView1.Rows.Count;
rowChanged = new bool[totalRows];
if (!Page.IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select * from items", con);
DataTable dt = new DataTable();
adap.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox thisTextBox = (TextBox)sender;
GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
int row = thisGridViewRow.RowIndex;
rowChanged[row] = true;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
int totalRows = GridView1.Rows.Count;
for (int r = 0; r < totalRows; r++)
{
if (rowChanged[r])
{
GridViewRow thisGridViewRow = GridView1.Rows[r];
HiddenField hf1 = (HiddenField)thisGridViewRow.FindControl("HiddenField1");
string pk = hf1.Value;
TextBox tb1 = (TextBox)thisGridViewRow.FindControl("TextBox1");
string name = tb1.Text;
TextBox tb2 = (TextBox)thisGridViewRow.FindControl("TextBox2");
decimal price = Convert.ToDecimal(tb2.Text);
SqlCommand cmd = new SqlCommand("update items set name='" + name + "' , price='" + price + "' where INTERM_NO=' " + pk + "'", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
lblMessage.Text = "Operation perform successfully";
con.Close();
}
}
}
GridView1.DataBind();
BindGrid();
}
}
}
Note: If you have any query or question about this post contact us:
or try this . this link was helpful for your requirement
Related
data is retrieved from the attendance table and the column name is status I want to change the status of the employee to 'leave' if the status of employee is other than 'present' and 'absent'
MY aspx design code
<asp:DropDownList ID="ddlStatus" runat="server" DataValueField="<%# statusConversion(Eval("Status")) %>">
<asp:ListItem value="Present" Text = "Present"></asp:ListItem>
<asp:ListItem value="Absent" Text="Absent"></asp:ListItem>
<asp:ListItem value="Leave" Text="Leave"></asp:ListItem>
</asp:DropDownList>ode here
MY C# backend function code
public String statusConversion(object myVal)
{
String p = "Present";
String a = "Absent";
String l = "Leave";
String val = myVal.ToString();
if (val.Equals(a) || val.Equals(p))
{
return val;
}
else
{
val = l;
return val;
}
}
According to your description, I suggest you could use gridview row databound method to achieve your requirement. You could set the dropdown’s select value in this method and use your custom method to check the stauts codes.
More details, you could refer to below codes:
ASPX:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="GridviewWithDDL.aspx.cs" Inherits="WebFormIdentityTest.GridviewWithDDL" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false" OnDataBound="GridView1_DataBound" >
<Columns>
<asp:BoundField DataField="id" HeaderText="Id" ItemStyle-Width="30" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Operation">
<ItemTemplate>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("Status") %>'/>
<asp:DropDownList ID="ddlStatus" runat="server" >
<asp:ListItem value="Present" Text = "Present"></asp:ListItem>
<asp:ListItem value="Absent" Text="Absent"></asp:ListItem>
<asp:ListItem value="Leave" Text="Leave"></asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Code-behind:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebFormIdentityTest
{
public partial class GridviewWithDDL : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable d1 = new DataTable();
d1.Columns.Add("id");
d1.Columns.Add("Status");
d1.Columns.Add("SelectSource");
d1.Columns.Add("SourceName");
d1.Rows.Add("1", "Present", "bbbb", "aaaaaaa");
d1.Rows.Add("2", "Absent", "ccccc", "dddddd");
d1.Rows.Add("3", "Leave", "dddd", "fffff");
d1.Rows.Add("4", "aaaa", "eeee", "ffff");
d1.Rows.Add("5", "Leave", "cccc", "asdasdas");
d1.Rows.Add("6", "bbb", "werwer", "qweqwe");
GridView1.DataSource = d1;
GridView1.DataBind();
}
public static String statusConversion(object myVal)
{
String p = "Present";
String a = "Absent";
String l = "Leave";
String val = myVal.ToString();
if (val.Equals(a) || val.Equals(p))
{
return val;
}
else
{
val = l;
return val;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void GridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
if (gvRow.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = gvRow.FindControl("ddlStatus") as DropDownList;
HiddenField hf = gvRow.FindControl("HiddenField1") as HiddenField;
ddl.SelectedValue = statusConversion(hf.Value);
}
}
}
}
}
Result:
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();
}
How to get gridview row values when checkbox is checked. I am using this code in button's click event, but it's not working .
Html Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%"
DataKeyNames="ReportId" OnRowDataBound="GridView2_OnRowDataBound" ForeColor="#333333"
PageSize="5" Style="text-align: center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxG1" runat="server" />
</ItemTemplate>
C# Code:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
if (CheckRow.Checked)
{
}
}
}
}
I can not see how you bound data and where is your button placement. So this is work sample.
<asp:Button Text="text" runat="server" OnClick="Unnamed_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ReportId" Width="100%"
ForeColor="#333333" PageSize="5" Style="text-align: center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxG1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = new RowModel[]
{
new RowModel { ReportId = "1" },
new RowModel { ReportId = "2" },
new RowModel { ReportId = "3" }
};
GridView1.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
if (CheckRow.Checked)
{
}
}
}
}
public class RowModel
{
public string ReportId { get; set; }
}
In My sample code I have consider manually data while binding gridview because as you don't specify how you have bind your gridview through database or not, but it should work in both approaches.
My HTML code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Checkbox Selected Row Values from Gridview in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnProcess" Text="Get Selected Records" runat="server" Font-Bold="true" onclick="btnProcess_Click" />
<br />
<asp:Label ID="lblmsg" runat="server" />
</div>
</form>
</body>
</html>
Code Behind: This is just for binding GridView with proper data
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
DataRow dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 1; //Bind Data to Columns
dtrow["UserName"] = "SureshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 2; //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 3; //Bind Data to Columns
dtrow["UserName"] = "MaheshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
Code of Button_Click event
protected void btnProcess_Click(object sender, EventArgs e)
{
string str = string.Empty;
string strname = string.Empty;
string edu = string.Empty;
string location = string.Empty;
foreach (GridViewRow gvrow in gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null & chk.Checked)
{
//To Fetch the row index
//str += gvDetails.SelectedIndex.ToString();
//To Fetch the value of Selected Row.
str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text + ',';
edu += gvrow.Cells[3].Text + ',';
location += gvrow.Cells[4].Text + ',';
}
}
str = str.Trim(",".ToCharArray());
strname = strname.Trim(",".ToCharArray());
lblmsg.Text = "Selected UserIds: <b>" + str + "</b><br/>" + "Selected UserNames: <b>" + strname + "</b><br>" + " Education: <b>" + edu + "</b><br>" + " Location: <b>" + location + "</b><br>";
}
protected void Button1_Click(object sender, EventArgs e)
{
int count= 0;
foreach (GridViewRow gvindex in GridView1.Rows)
{
CheckBox chck = gvrow.FindControl("CheckBoxG1") as CheckBox;
if (chck.Checked)
{
GridView1.EditIndex = count;
DataBind(); //Your Databind Function
}
count++;
}
Iam new to asp.net can anyone help me on this.
I want to make a dynamic grid in asp.net which have 5 drop down list binding from database
and on selection of first dropdownvalue second dropdown bind.and it has also add row & delete
row button.
<asp:UpdatePanel runat="server"><ContentTemplate>
<asp:GridView ID="grvparameterdetail" runat="server"
ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333"
GridLines="None" OnRowDeleting="grvparameterDetails_RowDeleting"
>
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="Company">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindcompany1() %>' DataTextField="Comp_Name" DataValueField="Comp_Code" ID="drpcompany" runat="server" AppendDataBoundItems="true" AutoPostBack="true" OnSelectedIndexChanged="drpcompany_indexedchanged">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Center">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindunit1() %>' DataTextField="center" DataValueField="Pub_cent_Code" ID="drpcenter" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publ.Type">
<ItemTemplate>
<asp:DropDownList DataSource='<%# bindptype1() %>' DataTextField="pubname" DataValueField="pubtypecode" ID="drppubtype" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Publication">
<ItemTemplate>
<asp:DropDownList ID="drppub" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edition">
<ItemTemplate>
<asp:DropDownList ID="drppubed" runat="server" AppendDataBoundItems="true">
<asp:ListItem Value="-1">Select</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server"
Text="Add New Row" OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
aspx.cs code
if (!Page.IsPostBack)
{
FirstGridViewRow();
}
private void FirstGridViewRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Col1", typeof(string)));
dt.Columns.Add(new DataColumn("Col2", typeof(string)));
dt.Columns.Add(new DataColumn("Col3", typeof(string)));
dt.Columns.Add(new DataColumn("Col4", typeof(string)));
dt.Columns.Add(new DataColumn("Col5", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
//dr["Col2"] = string.Empty;
//dr["Col3"] = string.Empty;
//dr["Col4"] = string.Empty;
//dr["Col5"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
grvparameterdetail.DataSource = dt;
grvparameterdetail.DataBind();
}
private void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = dtCurrentTable.Rows.Count + 1;
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
for (int i = 1; i <= dtCurrentTable.Rows.Count - 1; i++)
{
DropDownList Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
//drCurrentRow = dtCurrentTable.NewRow();
//drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i]["Col1"] = Drpcompany.SelectedValue;
dtCurrentTable.Rows[i]["Col2"] = drpcenter.SelectedValue;
dtCurrentTable.Rows[i]["Col3"] = drppubtype.SelectedValue;
dtCurrentTable.Rows[i]["Col4"] = Drppublication.SelectedIndex;
dtCurrentTable.Rows[i]["Col5"] = Drpedition.SelectedValue;
rowIndex++;
}
//dtCurrentTable.Rows.Add(drCurrentRow);
//ViewState["CurrentTable"] = dtCurrentTable;
grvparameterdetail.DataSource = dtCurrentTable;
grvparameterdetail.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
DropDownList Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
Drpcompany.SelectedValue = dt.Rows[i]["Col1"].ToString();
drpcenter.SelectedValue = dt.Rows[i]["Col2"].ToString();
drppubtype.SelectedValue = dt.Rows[i]["Col3"].ToString();
Drppublication.SelectedValue = dt.Rows[i]["Col4"].ToString();
Drpedition.SelectedValue = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}
protected void grvparameterDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
SetRowData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
int rowIndex = Convert.ToInt32(e.RowIndex);
if (dt.Rows.Count > 1)
{
dt.Rows.Remove(dt.Rows[rowIndex]);
drCurrentRow = dt.NewRow();
ViewState["CurrentTable"] = dt;
grvparameterdetail.DataSource = dt;
grvparameterdetail.DataBind();
for (int i = 0; i < grvparameterdetail.Rows.Count - 1; i++)
{
grvparameterdetail.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
}
SetPreviousData();
}
}
}
private void SetRowData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
DropDownList Drpcompany =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[1].FindControl("drpcompany");
DropDownList drpcenter =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[2].FindControl("drpcenter");
DropDownList drppubtype =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[3].FindControl("drppubtype");
DropDownList Drppublication =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[4].FindControl("drppub");
DropDownList Drpedition =
(DropDownList)grvparameterdetail.Rows[rowIndex].Cells[5].FindControl("drppubed");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = Drpcompany.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col2"] = drpcenter.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col3"] = drppubtype.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col4"] = Drppublication.SelectedValue;
dtCurrentTable.Rows[i - 1]["Col5"] = Drpedition.SelectedValue;
rowIndex++;
}
ViewState["CurrentTable"] = dtCurrentTable;
//grvStudentDetails.DataSource = dtCurrentTable;
//grvStudentDetails.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//SetPreviousData();
}
protected void drpcompany_indexedchanged(object sender, EventArgs e)
{
//what to write here
}
Thanks in advance.
I have made a sample code , it wil be easy to get an idea how to start ur task..
i have done harcoded data.. instead of hardcoding use the data from db..
chk the comments ...
Page 1 : aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery.js.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>Last Name</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td>Speciality</td>
<td>
<asp:DropDownList ID="ddlSpeciality" runat="server">
<asp:ListItem Text="" />
<asp:ListItem Text="aaa" />
<asp:ListItem Text="bbb" />
<asp:ListItem Text="ccc" />
</asp:DropDownList></td>
</tr>
<tr>
<td>Location</td>
<td>
<asp:DropDownList ID="ddlLocation" runat="server">
<asp:ListItem Text="" />
<asp:ListItem Text="bangalore" />
<asp:ListItem Text="chennai" />
<asp:ListItem Text="hyderabad" />
</asp:DropDownList></td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" /></td>
</tr>
</table>
</form>
</body>
</html>
Page 1: cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSearch_Click(object sender, EventArgs e)
{
string lastName = txtLastName.Text.Trim();
string speciality = ddlSpeciality.Text;
string location = ddlLocation.Text;
Response.Redirect(string.Format("page2.aspx?lastname={0}&speciality={1}&location={2}",lastName ,speciality , location));
}
}
}
Page 2: aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="page2.aspx.cs" Inherits="WebApplication1.test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvdata" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkID" OnClick="LinkButton1_Click" Text="Details" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Page 2: cs file
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) { }
else
{
string lastname = Request.QueryString["lastname"];
string speciality = Request.QueryString["speciality"];
string location = Request.QueryString["location"];
string query = lastname.Length == 0 ? "" : "lastname ='" + lastname + "' and";
query += speciality.Length == 0 ? "" : "speciality ='" + speciality + "' and";
query += location.Length == 0 ? "" : "location ='" + location + "' ";
query = query.Trim().TrimStart(new char[] { 'a', 'n', 'd' }).TrimEnd(new char[] { 'a', 'n', 'd' });
query = "select * from tablename where " +( query.Length == 0 ? "1=1" : query);
// use this query to get data from sql database
// use shld get the data from db
// for example, i have hardcoded the datatable with some values
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("lastname", typeof(string));
dt.Columns.Add("speciality", typeof(string));
dt.Columns.Add("location", typeof(string));
dt.Rows.Add(1, "karthik", "aaa", "bangalore");
dt.Rows.Add(2, "parthip", "aaa", "chennai");
dt.Rows.Add(3, "krishna", "aaa", "hyderabad");
gvdata.DataSource = dt;
gvdata.DataBind();
}
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
string id = ((sender as LinkButton).Parent.Parent as GridViewRow).Cells[1].Text;
Response.Redirect("page3.aspx?id=" + id);
}
}
}
Page 3: aspx file
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="page3.aspx.cs" Inherits="WebApplication1.page3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div runat="server" id="divcontent">
</div>
</form>
</body>
</html>
Page 3: cs file
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class page3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) { }
else
{
string id = Request.QueryString["id"];
// use this id to fetch the data from db to get the details.
// get the data from db..
// i have hardcoded
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("lastname", typeof(string));
dt.Columns.Add("speciality", typeof(string));
dt.Columns.Add("location", typeof(string));
dt.Rows.Add(1, "karthik", "aaa", "bangalore");
Table tbl = new Table() { CellPadding=1 , CellSpacing=2 , BorderColor = System.Drawing.Color.Red, BorderWidth=1 };
foreach (DataColumn col in dt.Columns)
{
TableRow tr = new TableRow() { BorderWidth=1 , BorderColor = System.Drawing.Color.Red };
tr.Cells.Add( new TableCell () { BorderWidth=1 , BorderColor = System.Drawing.Color.Red ,Text = col.ColumnName});
tr.Cells.Add( new TableCell () { BorderWidth=1 , BorderColor = System.Drawing.Color.Red ,Text = dt.Rows[0][col].ToString()});
tbl.Rows.Add(tr);
}
divcontent.Controls.Add(tbl);
}
}
}
}
I have a gridview with textboxes for item no, desc qty, cost, extncost. When itemno entered in the textbox desc and cost of the item will comes automatically by on textbox event change.
Here when i add a new row in the grid view, values of last entered value got disappears.
when i am checking using break point i can able to see the last entered values in data table.
Since, while adding new row has blank text boxes, now system considers blank text box for on text change event. So, last entered values also not displaying. Text box changes in one row also affects in other rows.
Here is the ASPX.page code:
<asp:UpdatePanel ID="gin_pnlupdt" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="grv_gindet" runat="server" ShowFooter="True" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" OnRowDeleting="grvStudentDetails_RowDeleting"
OnRowDataBound="grv_gindtrowcmd" OnRowCommand="grv_gindetrowcmd">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="SNo" />
<asp:TemplateField HeaderText="Item Number">
<ItemTemplate>
<asp:TextBox ID="txt_itemno" runat="server" OnTextChanged="txt_itemno_changed" AutoPostBack="True"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Description">
<ItemTemplate>
<asp:Label ID="txt_itemdesc" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txt_qty" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Cost">
<ItemTemplate>
<asp:Label ID="txt_ucost" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Extended Cost">
<ItemTemplate>
<asp:Label ID="txt_extncost" runat="server"></asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="BtnAddRow" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowDeleteButton="True" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<EditRowStyle BackColor="#2461BF" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="grv_gindet" />
</Triggers>
</asp:UpdatePanel>
Here is the CS code for add new row:
protected void AddNewRow()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
TextBox TextBoxItem =
(TextBox)grv_gindet.Rows[rowIndex].Cells[1].FindControl("txt_itemno");
Label TextBoxDesc =
(Label)grv_gindet.Rows[rowIndex].Cells[2].FindControl("txt_itemdesc");
TextBox TextBoxQty =
(TextBox)grv_gindet.Rows[rowIndex].Cells[3].FindControl("txt_qty");
Label TextBoxucost =
(Label)grv_gindet.Rows[rowIndex].Cells[4].FindControl("txt_ucost");
Label TextBoxextncost =
(Label)grv_gindet.Rows[rowIndex].Cells[5].FindControl("txt_extncost");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxItem.Text;
dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxDesc.Text;
dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxQty.Text;
dtCurrentTable.Rows[i - 1]["Col4"] = TextBoxucost.Text;
dtCurrentTable.Rows[i - 1]["Col5"] = TextBoxextncost.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
grv_gindet.DataSource = dtCurrentTable;
grv_gindet.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
SetPreviousData();
}
Code for retrive Previous data:
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
TextBox TextBoxItem = (TextBox)grv_gindet.Rows[rowIndex].Cells[1].FindControl("txt_itemno");
Label TextBoxDesc = (Label)grv_gindet.Rows[rowIndex].Cells[2].FindControl("txt_itemdesc");
TextBox TextBoxQty =
(TextBox)grv_gindet.Rows[rowIndex].Cells[3].FindControl("txt_qty");
Label TextBoxucost =
(Label)grv_gindet.Rows[rowIndex].Cells[4].FindControl("txt_ucost");
Label TextBoxextncost =
(Label)grv_gindet.Rows[rowIndex].Cells[5].FindControl("txt_extncost");
TextBoxItem.Text = dt.Rows[i]["Col1"].ToString();
TextBoxDesc.Text = dt.Rows[i]["Col2"].ToString();
TextBoxQty.Text = dt.Rows[i]["Col3"].ToString();
TextBoxucost.Text = dt.Rows[i]["Col4"].ToString();
TextBoxextncost.Text = dt.Rows[i]["Col5"].ToString();
rowIndex++;
}
}
}
}
Textbox change event:
protected void txt_itemno_changed(object sender, EventArgs e)
{
//TextBox thisTextBox = (TextBox)sender;
//GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
//int row = thisGridViewRow.RowIndex;
GridViewRow currentrow = (GridViewRow)((TextBox)sender).Parent.Parent;
TextBox thisTextBox = (TextBox)currentrow.FindControl("txt_itemno");
int row = currentrow.RowIndex;
//rowChanged[row] = true;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AWCC"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ITEMDET.ITEMDESC,RGITEMDET.UNITCOST FROM ITEMDET JOIN RGITEMDET ON RGITEMDET.ITEMNO=ITEMDET.ITEMNO WHERE ITEMDET.ITEMNO ='" + thisTextBox.Text + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
grv_gindet.Rows[row].Cells[2].Text = dr["ITEMDESC"].ToString();
grv_gindet.Rows[row].Cells[4].Text = dr["UNITCOST"].ToString();
}
}
thisTextBox.Enabled = false;
}
Postback control code for gridview child element:
protected void grv_gindtrowcmd(object sender, GridViewRowEventArgs e)
{
try
{
TextBox txtitm = e.Row.FindControl("txt_itemno") as TextBox;
LinkButton lnkbtn = e.Row.FindControl("ShowDeleteButton") as LinkButton;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(txtitm);
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(lnkbtn);
}
catch
{
}
}
protected void grv_gindetrowcmd(object sender, GridViewCommandEventArgs e)
{
try
{
Button btnad = grv_gindet.FooterRow.FindControl("ButtonAdd") as Button;
ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(btnad);
}
catch
{
}
}
Kinldy provide a solution ASAP, do the needful.
I hope this will help you, change this in Textchange event
GridViewRow currentrow = (GridViewRow)((TextBox)sender).Parent.Parent.Parent.Parent;
TextBox thisTextBox = (TextBox)currentrow.FindControl("txt_itemno");
if (!string.IsNullOrWhiteSpace(thisTextBox.Text))
{
int row = currentrow.RowIndex;
//rowChanged[row] = true;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["AWCC"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT ITEMDET.ITEMDESC,RGITEMDET.UNITCOST FROM ITEMDET JOIN RGITEMDET ON RGITEMDET.ITEMNO=ITEMDET.ITEMNO WHERE ITEMDET.ITEMNO ='" + thisTextBox.Text + "' ", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
((Label)(grv_gindet.Rows[row].FindControl("txt_itemdesc"))).Text = dr["ITEMDESC"].ToString();
((TextBox)(grv_gindet.Rows[row].FindControl("txt_ucost"))).Text = dr["UNITCOST"].ToString();
}
con.Close();
}
thisTextBox.Enabled = false;
}