I use auto edit button of gridview control in my asp.net project. I facing a problem when i click edit button it fires rowcommand event and rowediting event of gridview but grid row not goes in edit mode when i again click edit button now grid row goes in edit mode problem is that why i need to click edit button two times.
Here is my html (aspx) code.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="LMS.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="GridView1" runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowCommand="GridView1_RowCommand" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" AutoGenerateEditButton="True">
<Columns>
<asp:BoundField HeaderText="Employee Number" DataField="empno" ReadOnly="True">
<ItemStyle Width="100px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Employee Name">
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="gridheader" />
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
C# Code
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.Xml.Linq;
using System.Xml;
namespace LMS
{
public partial class test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[1] {new DataColumn("empno", typeof(int))});
for (int i = 0; i < 10; i++)
{
DataRow dr;
dr = dt.NewRow();
dr["empno"] = i.ToString("00");
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridView1.EditIndex = -1;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
}
}
}
Add .DataBind into GridView1_RowEditing:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[1] { new DataColumn("empno", typeof(int)) });
for (int i = 0; i < 10; i++)
{
DataRow dr;
dr = dt.NewRow();
dr["empno"] = i.ToString("00");
dt.Rows.Add(dr);
GridView1.DataSource = dt;
Session["dt"] = dt;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = Session["dt"] as DataTable;
GridView1.DataBind();
}
Related
I have found a dynamic gridview code that creates lines and saves the one you filled last.
In my code i want to parse the droplist selected value text instead of actually writing in the textbox.
I have managed to parse the selectedvalue text in a textbox and for one line everything goes fine, but when i try to create a second line the selected value becomes the same for both lines.
(example: lets say i have a ddl menu with the values "a,b" if i choose the a value first the textbox will be filled ok "a" value, but if i choose b for the second line it will be both "b".
I will be needing 9 textboxes but i have made a simple version of the code containing only 1 textbox for the sake of space.
HTML
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication4.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div style="height: 337px">
<asp:GridView ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false" OnSelectedIndexChanged="Gridview1_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row"
OnClick="ButtonAdd_Click" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
C# code
namespace WebApplication4
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
setInitialRow();
}
}
protected void Gridview1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
private void setInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dt.Rows.Add(dr);
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
private void AddNewRowToGrid()
{
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 box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.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++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
box1.Text = dt.Rows[i]["Column1"].ToString();
rowIndex++;
}
}
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
So as you'd imagine i tried going
box1.Text = DropDownList1.SelectedValue.ToString();
I tried with view state, but generally i failed.
Thanks for any of the answers guys!
ASPX Page
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
Code Behind
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SetPreviousData();
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
TextBox box1 = (TextBox)Gridview1.Rows[(dt.Rows.Count - 1)].Cells[1].FindControl("TextBox1");
box1.Text = DropDownList1.SelectedValue;
}
}
}
Another Approach you can try is you can directly place dropdownlist in gridview instead of textbox.
in my asp gird asp grid paging is not working what is the problem is my code please help me.. problem is when i click the paging items page is not post back..
here is my aspx code:
<asp:GridView ID="GridView1" Font-Size = "11pt" OnRowCommand="GridView1_RowCommand" AllowPaging="true" AllowSorting="true" PagerSettings-Visible="true" PageSize="4" CssClass="footable" runat="server" AutoGenerateColumns="false"
Style="max-width: 500px" DataKeyNames="Id" EnableViewState="true" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:ButtonField CommandName="Edit" ButtonType="Image" ImageUrl="~/image/redit.png" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="ProductDescription" HeaderText="Description" />
<asp:TemplateField>
<ItemTemplate>
<img src='data:image/jpg;base64,<%# Eval("ProductImage") != System.DBNull.Value ? Convert.ToBase64String((byte[])Eval("ProductImage")) : string.Empty %>' alt="image" height="80" width="80" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="Delete" ButtonType="Image" ImageUrl="~/image/rdelete.png" />
</Columns>
<PagerStyle HorizontalAlign = "Right" />
</asp:GridView>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/0.1.0/css/footable.min.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-footable/0.1.0/js/footable.min.js"></script>
<script type="text/javascript">
$(function () {
$('[id*=GridView1]').footable();
});
</script>
and here is my aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
LoadGrid();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.GridView1.DataKeys[rowIndex]["Id"];
if (e.CommandName == "Edit")
{
}
else if (e.CommandName == "Delete")
{
}
}
public void LoadGrid()
{
try
{
BusinessLogic.clsGeneral objGen = new BusinessLogic.clsGeneral();
string strquery = "select * from Products where status = 1";
DataTable dt = objGen.ExecuteQueryReturnDatatable(strquery);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
catch (Exception)
{
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
try like this:
You need to Bind Your GridView Again in PageIndexChanging event
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
LoadGrid();
}
Add datasource agin to your paging,
Try replacing the below snippet from yours.
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BusinessLogic.clsGeneral objGen = new BusinessLogic.clsGeneral();
string strquery = "select * from Products where status = 1";
DataTable dt = objGen.ExecuteQueryReturnDatatable(strquery);
GridView1.DataSource = dt;
GridView1.DataBind();
}
some points still here to be mentioned
Avoid inLine queries, that doesn't seems good
inspite calling data all over again to bind, you can use some other trick as well.
And in Sql ,never return *(all) , return only sets of column you need, * is not good practice.
Eg. select name,address,phone from .... instead of select *...
BundleTable.EnableOptimizations = false;
bundles.Add(new ScriptBundle("~/Scripts/jquery").Include(
"~/Scripts/jquery-1.11.2.min.js",
"~/Scripts/jquery.ui.min.js"
));
bundles.Add(new ScriptBundle("~/Scripts/customscripts").Include(
"~/Scripts/BeatPicker.min.js",
"~/Scripts/chosen.jquery.js",
"~/Scripts/legacy.js",
"~/Scripts/custombox.js",
"~/Scripts/ion.rangeSlider.js",
"~/Scripts/ion.rangeSlider.min.js",
"~/Scripts/iCheck/icheck.min.js",
// "~/Scripts/jquery.ui.datepicker1.min.js",
"~/Scripts/jquery.dataTables.min.js",
"~/Scripts/jquery.ui.datepicker.monthyearpicker.js",
"~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Scripts/jquery.akordeon.js",
"~/Scripts/jquery.autogrow-min.js",
"~/Scripts/jquery.corner.js",
Heres My Code
Timesheet.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Timesheet.aspx.cs" Inherits="Timesheet" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true" OnRowDataBound="OnRowDataBound" PageIndex="0" PageSize="20">
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
Timesheet.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;
using TimesheetBLL;
public partial class Timesheet : System.Web.UI.Page
{
clsTimesheetBLL bll = new clsTimesheetBLL();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
BoundField bfield = new BoundField();
bfield.HeaderText = "Rig / Task";
bfield.DataField = "rigtask";
GridView1.Columns.Add(bfield);
DataTable dt2 = bll.GetEmp();
if (dt2.Rows.Count > 0)
{
for (int i = 0; i < dt2.Rows.Count; i++)
{
TemplateField tfield = new TemplateField();
tfield.HeaderText = dt2.Rows[i]["name"].ToString();
GridView1.Columns.Add(tfield);
}
}
TemplateField tfield2 = new TemplateField();
tfield2.HeaderText = "Total";
GridView1.Columns.Add(tfield2);
DataTable dt = bll.GetRigTask();
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}`enter code here`
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataTable dt2 = bll.GetEmp();
if (dt2.Rows.Count > 0)
{
for (int i = 1; i <= dt2.Rows.Count; i++)
{
TextBox txtCountry = new TextBox();
txtCountry.ID = "txtCountry";
e.Row.Cells[i].Controls.Add(txtCountry);
}
Label lblTotal = new Label();
lblTotal.ID = "lblTotal";
e.Row.Cells[dt2.Rows.Count + 1].Controls.Add(lblTotal);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
var total = 0;
foreach (GridViewRow row in GridView1.Rows)
{
TextBox txtTotal = new TextBox();
txtTotal = (TextBox)row.FindControl("txtCountry");
total += Convert.ToInt32(txtTotal.Text);
}
}
}
All the columns and rows are dynamically generated and using two different tables please help me if user enter its hour then its show the the total in last column(Total)[Totals hours on project].
and in footer for each employee.
And it will be great help if some one can tell how to store it in database.
I have created a datatable globaly and i have add columns to it in the page load event.
Now i want to add data to it in a button click event..
When I do it as below I get a error saying....
Column 'catID' does not belong to table
What is the solution... Do i need to use sessions... ? the code is like below
public partial class Default2 : System.Web.UI.Page
{
DataTable dtSelectedSeats = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dtSelectedSeats.Columns.Add("catID", typeof(string));
dtSelectedSeats.Columns.Add("seatID", typeof(string));
}
}
protected void seat_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (button.BackColor == Color.Cyan)
{
button.BackColor = Color.Lime;
addSeat(button.Text);
}
}
private void addSeat(string seatNo)
{
DataRow dr;
dr = dtSelectedSeats.NewRow();
dr["catID"] = ddlCategory.SelectedItem.Value.ToString();
dr["seatID"] = seatNo;
dtSelectedSeats.Rows.Add(dr);
}
}
ASPX:
<asp:DropDownList ID="ddlCategory" runat="server">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="seat" runat="server" BackColor="Cyan" onclick="seat_Click" Text="1" />
<asp:Button ID="Button1" runat="server" BackColor="Cyan" onclick="Button1_Click" Text="2" />
<asp:Button ID="Button2" runat="server" BackColor="Cyan" onclick="Button2_Click" Text="3" /><br />
<asp:GridView ID="GridView1" runat="server"/>
Code behind:
protected void seat_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
if (button.BackColor == Color.Cyan)
{
button.BackColor = Color.Lime;
addSeat(button.Text);
}
}
private void addSeat(string seatNo)
{
if (Session["dt"] == null)
{
Response.Write("DataTable not exist!");
return;
}
DataTable dtSelectedSeats = (DataTable)Session["dt"];
DataRow dr = dtSelectedSeats.NewRow();
dr["catID"] = ddlCategory.SelectedItem.Value.ToString();
dr["seatID"] = seatNo;
dtSelectedSeats.Rows.Add(dr);
GridView1.DataSource = dtSelectedSeats;
GridView1.DataBind();
Session["dt"] = dtSelectedSeats;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dtSelectedSeats = new DataTable();
dtSelectedSeats.Columns.Add("catID", typeof(string));
dtSelectedSeats.Columns.Add("seatID", typeof(string));
Session["dt"] = dtSelectedSeats;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
seat_Click(sender, e);
}
protected void Button2_Click(object sender, EventArgs e)
{
seat_Click(sender, e);
}
just remove the if (!IsPostBack)
coz when you click the button , the page will post back.
Your Code is perfectly correct for DataTable, the error you are getting may be for some different problem. Please specify correctly your error
Just off the top of my head it looks as if you are adding the rows in the wrong event. I'm not sure your DataTable has been initialized at the point you are adding columns to it (thus throwing away your changes). Try putting your PageLoad code into PagePrerender and see if that gives you a better result.
I am making an editable GridView, but my problem is that whenever I click on a button nothing happens. When I click a second time I see what happened during the previous click.
aspx
<%# Page Title="Home Page" Language="C#"
MasterPageFile="~/Site.master" AutoEventWireup="true"
EnableEventValidation="true"
CodeBehind="Default.aspx.cs" Inherits="BeheerSysteemWeb._Default" %>
<asp:Content ID="HeaderContent" runat="server"
ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content
ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
<asp:GridView ID="GridView1" runat="server"
onrowcancelingedit="GridView1_RowCancelingEdit"
onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating" AutoGenerateColumns="False">
<Columns>
<asp:CommandField ButtonType="Button" ShowEditButton="true" ShowCancelButton="true" />
<asp:TemplateField HeaderText="36">
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtSpoor" Text="TramNummer" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</h2>
</asp:Content>
Codebehind
namespace BeheerSysteemWeb
{
public partial class _Default : System.Web.UI.Page
{
List<string> leeg = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
leeg.Add("");
leeg.Add("");
leeg.Add("");
leeg.Add("");
GridView1.DataSource = leeg;
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox txtSpoor = (TextBox)row.FindControl("txtSpoor");
e.Cancel = true;
GridView1.EditIndex = -1;
}
}
}
How can I get the button to work in ASP.NET ?
I am not sure if this is the issue here, but you need to add your data on every page call, and make DataBind after the actions as:
public partial class _Default : System.Web.UI.Page
{
List<string> leeg = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
LoadData();
if (!Page.IsPostBack)
{
GridView1.DataBind();
}
}
private void LoadData()
{
leeg.Add("");
leeg.Add("");
leeg.Add("");
leeg.Add("");
GridView1.DataSource = leeg;
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
e.Cancel = true;
GridView1.EditIndex = -1;
GridView1.DataBind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
TextBox txtSpoor = (TextBox)row.FindControl("txtSpoor");
e.Cancel = true;
GridView1.EditIndex = -1;
GridView1.DataBind();
}
}
Try that to see if you solve your issue.
You will have to rebind the data call LoadData() both on GridView1_RowEditing & GridView1_RowCancelingEdit
You can refer to http://dotnetdiscussion.wordpress.com/2007/09/26/aspnet-gridview-updateeditcancel-hyperlinkfields-and-datakey-retrieval/
Happy Coding!!!