How to add rows to a data table - c#

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.

Related

how to change gridview paging when have search result

I have gridview and some textbox that user can search .
when user search I updated gridview but when changed pageing I bind gridview again and I lost search result .
how can I change gridview paging without call DataBind Again?
I used this for Paging:
protected void grv_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Data.PageIndex = e.NewPageIndex;
TicketDataBinding();
}
and my search method is :
protected void btn_search_Click(object sender, EventArgs e){
using (var ticket = new BLL.Ticket())
{
grv_Data.DataSource = tit.SelectList( fromDate, toDate);
grv_Data.DataBind();
}}
sorry I forgot asp.net webform and I dont know how do this ?
I've included two examples of binding data to a GridView where paging still works on filtered data. I hope it helps you.
1.You can do this completely in .ASPX:
<form id="form1" runat="server">
<asp:TextBox ID="txtEmailAddress" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Search" />
<asp:GridView ID="GridView1" runat="server" DataSourceID="sqlDS" AllowPaging="true" PageSize="5" AutoGenerateColumns="true">
<Columns>
<asp:BoundField DataField="EmailType" />
<asp:BoundField DataField="EmailAddress" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlDS"
runat="server"
ConnectionString="<%$ ConnectionStrings:conn %>"
SelectCommand="SELECT EmailType, EmailAddress FROM EmailNotifications WHERE EmailAddress LIKE #EmailAddressParam + '%'">
<SelectParameters>
<asp:ControlParameter ControlID="txtEmailAddress" DbType="String" Name="EmailAddressParam" DefaultValue="%" />
</SelectParameters>
</asp:SqlDataSource>
</form>
2.Or in code behind:
public partial class PagingAndSearchingInGridView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.GetData();
}
private void GetData()
{
string emailAddress = txtEmailAddress.Text;
DataTable table = !Page.IsPostBack ? GetEmails() : GetEmails(emailAddress);
GridView1.DataSource = table;
GridView1.DataBind();
}
private DataTable GetEmails(string emailAddress = "%")
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand("SELECT EmailType, EmailAddress FROM EmailNotifications WHERE EmailAddress LIKE #EmailAddressParam + '%'", connection))
{
command.Parameters.AddWithValue("#EmailAddressParam", emailAddress);
using (var a = new SqlDataAdapter(command))
{
connection.Open();
a.Fill(table);
connection.Close();
}
}
}
return table;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
this.GetData();
}
}
While the pageIndex changed event, you can check whether the search button is already clicked or not. When clicking the search button you can set a hiddenfield value to 1 or something like that.
protected void grv_Data_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grv_Data.PageIndex = e.NewPageIndex;
if(status==1) //Search button is already clicked, means the grid contains searched result
{
grv_Data.DataSource = tit.SelectList( fromDate, toDate);
}
else
{
//Search button is not clicked .. means the grid contains all records.
TicketDataBinding();
}
}

Binding RadGrid To DataTable ASP.NET

What i am trying to do is that before saving records to database i want to show the records in GridView that is when user fill the text box and click on button the record is to be shown on GridView with serial Number 1 , 2 , 3 ...
So far i have approach this . The first records get added successfully but when adding second record the DataTable give null reference exception . Is this the right approach ? Or is there an easy way to do this . I am using Telerik RadGrid for asp.net .
public DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dt = new DataTable();
dt.Columns.Add("Sn#");
dt.Columns.Add("type");
dt.Columns.Add("AccountTitle");
dt.Columns.Add("Description");
dt.Columns.Add("CostCenter");
dt.Columns.Add("Debit");
dt.Columns.Add("Credit");
sno.Text = "1";
}
}
protected void radGridView2_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
dt = AddRow(dt); // call the method to create row
ViewState["dt"] = dt;
dt = (DataTable)ViewState["dt"];
radGridView2.DataSource = dt;
}
private DataTable AddRow(DataTable dt)
{ // method to create row
DataRow dr = dt.NewRow();
dr[0] = sno.Text;
dr[1] = type.Text;
dr[2] = htitle.Text;
dr[3] = disc.Text;
dr[4] = job.SelectedItem.Text;
dr[5] = drr.Text;
dr[6] = crr.Text;
dt.Rows.Add(dr);
return dt;
}
protected void b1_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)ViewState["dt"];
ViewState["dt"] = AddRow(dt);
radGridView2.Rebind();
Session["cttt"] = Convert.ToInt32(sno.Text)+1;
sno.Text = Session["cttt"].ToString();
}
I have copy your code and change a bit. Due to your dt declared twice. I believe your error will be the DataTable is null
.aspx
<asp:ScriptManager ID="sm" runat="server"></asp:ScriptManager>
<div>
<telerik:RadGrid ID="rg" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource"></telerik:RadGrid>
<br />
<asp:TextBox ID="sno" runat="server"></asp:TextBox><br />
<asp:TextBox ID="type" runat="server" Text="A"></asp:TextBox><br />
<asp:TextBox ID="htitle" runat="server" Text="B"></asp:TextBox><br />
<asp:TextBox ID="disc" runat="server" Text="C"></asp:TextBox><br />
<asp:DropDownList ID="job" runat="server"><asp:ListItem>Yeah</asp:ListItem></asp:DropDownList><br />
<asp:TextBox ID="drr" runat="server" Text="D"></asp:TextBox><br />
<asp:TextBox ID="crr" runat="server" Text="E"></asp:TextBox><br />
<br />
<br />
<asp:Button ID="b1" runat="server" Text="Click" OnClick="b1_Click" />
</div>
</asp:ScriptManager>
.cs
private DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
sno.Text = "1";
}
}
private DataTable CreateDataTable()
{
dt = new DataTable();
dt.Columns.Add("Sn#");
dt.Columns.Add("type");
dt.Columns.Add("AccountTitle");
dt.Columns.Add("Description");
dt.Columns.Add("CostCenter");
dt.Columns.Add("Debit");
dt.Columns.Add("Credit");
return dt;
}
private DataTable AddRow(DataTable dt1)
{ // method to create row
DataRow dr = dt1.NewRow();
dr[0] = sno.Text;
dr[1] = type.Text;
dr[2] = htitle.Text;
dr[3] = disc.Text;
dr[4] = job.SelectedItem.Text;
dr[5] = drr.Text;
dr[6] = crr.Text;
dt1.Rows.Add(dr);
return dt1;
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
rg.DataSource = ViewState["dt"] as DataTable;
}
protected void b1_Click(object sender, EventArgs e)
{
DataTable dt1 = ViewState["dt"] != null ? ViewState["dt"] as DataTable : CreateDataTable();
ViewState["dt"] = AddRow(dt1);
rg.Rebind();
Session["cttt"] = Convert.ToInt32(sno.Text) + 1;
sno.Text = Session["cttt"].ToString();
}
Result
You are creating a variable with the same name as the global variable (dt) in the event b1_click - this is causing the confusion and the error.
protected void b1_Click(object sender, EventArgs e)
{
//Use the global variable dt
//DataTable dt = (DataTable)ViewState["dt"];
dt = (DataTable)ViewState["dt"];
ViewState["dt"] = AddRow(dt);
radGridView2.Rebind(); //Note this would call the NeedDataSource event
Session["cttt"] = Convert.ToInt32(sno.Text)+1;
sno.Text = Session["cttt"].ToString();
}
Another point to note here is that the AddRow method will be called twice on the button click. Once from b1_click event and then again from NeedDataSource event (which gets triggered on radGridView2.Rebind())

Access gridview rows after postback

Good day!
I need to dynamycally upload files and display information in gridview.
After file upload, i need to select file type in dropdown.
But after postback i can't access Gridview1 rows, and get selected file types. After postback Gridview1.Rows.Count = 0.
Is it possible to get selected values from DropDownLists?
<asp:GridView ID="GridView1" runat="server" ShowHeader="False" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="FileName" />
<asp:TemplateField HeaderText="FileType">
<ItemTemplate>
<asp:DropDownList runat="server">
<asp:ListItem Value="Val1">Val1</asp:ListItem>
<asp:ListItem Value="Val2">Val2</asp:ListItem>
<asp:ListItem Value="Val3">Val3</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField DeleteText="Remove" ShowDeleteButton="true" />
</Columns>
</asp:GridView>
<asp:FileUpload ID="FileUpload" runat="server" onchange="this.form.submit()" />
Thanks
In Page_Load, during PostBack, GridView rows is empty.
protected void Page_Load(object sender, EventArgs e)
{
RestoreForm();
if (IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
FilesGridView.RowDeleting += new GridViewDeleteEventHandler(RemoveFileFromTable);
}
private void AddRow(string file)
{
DataTable dt = (DataTable)Page.Session["Files"];
if (dt == null)
{
AddDataTableToSession();
dt = (DataTable)Page.Session["Files"];
}
DataRow dr = dt.NewRow();
dr["FileName"] = file;
dr["FileType"] = 0;
dt.Rows.Add(dr);
Page.Session["Files"] = dt;
FilesGridView.DataSource = dt;
FilesGridView.DataBind();
}
private void AddDataTableToSession()
{
DataTable dt = new DataTable("Files");
DataColumn dc = new DataColumn("FileName", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("FileType", Type.GetType("System.String"));
dt.Columns.Add(dc);
Page.Session["Files"] = dt;
}
private void RemoveFileFromTable(object sender, GridViewDeleteEventArgs e)
{
int recordToDelete = e.RowIndex;
DataTable dt = (DataTable)Page.Session["Files"];
int cn = dt.Rows.Count;
dt.Rows.RemoveAt(recordToDelete);
dt.AcceptChanges();
Page.Session["Files"] = dt;
FilesGridView.DataSource = dt;
FilesGridView.DataBind();
}
Try by changing Ispostback like this.
if (!IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
(or)
if (IsPostBack == false && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
So that, if page load occurs, Your if condition will get true.
You can find the drop down list and update it with the value in the RowDataBOund event of gridview as follows
protected void Page_Load(object sender, EventArgs e)
{
//RestoreForm();
if (IsPostBack && FileUpload.HasFile)
{
AddRow(FileUpload.PostedFile.FileName);
}
else
{
AddDataTableToSession();
}
FilesGridView.RowDeleting += new GridViewDeleteEventHandler(RemoveFileFromTable);
FilesGridView.RowDataBound += KBFilesGridView_RowDataBound;
}
and row databound will be as follows
void KBFilesGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
DataRow dr= ((DataRowView)e.Row.DataItem).Row;
ddl.SelectedValue = dr["FileType"].ToString();
}
}
Similary you can get the value of dropdown for remove method as well as follows
private void RemoveFileFromTable(object sender, GridViewDeleteEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = e.Row.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
if(ddl.SelectedValue == "someValue") doSomeThing();
}
}
}

Button does not submit on first click, but on subsequent click submits previous information

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!!!

How to create gridview updating event dynamically?

public partial class Gridvw_expt2 : System.Web.UI.Page
{
SqlCommand com;
SqlDataAdapter da;
DataSet ds;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["gj"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
com = new SqlCommand("Select * from tblExpt",con);
da = new SqlDataAdapter(com);
ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows[0] != null)
{
GridView1.AutoGenerateEditButton = true;
GridView1.DataSource = ds;
GridView1.DataBind();
GridView1.RowUpdating += new GridViewUpdateEventHandler(abc);
GridView1.DataKeyNames = new string[] { "id" };
GridView1.RowEditing += new GridViewEditEventHandler(bc);
}
else
Response.Write("fkj");
}
protected void abc(object sender, GridViewUpdateEventArgs e)
{
Response.Write(e.RowIndex);
}
protected void bc(object sender, GridViewEditEventArgs e)
{
GridView gv = (GridView)sender;
gv.EditIndex = e.NewEditIndex;
}
}
the row used to get in edit mode only if i edit the next row means first row never get in edited mode.Please help why so.
Istead of
GridView1.Attributes.Add("onrowupdating", "abc");
do this:
GridView1.RowUpdating += new GridViewUpdateEventHandler(abc);
Also, Instead of
GridView1.Attributes.Add("DataKeyNames", "id");
do this
GridView1.DataKeyNames = new string[] { "id" };
Also x 2, Instead of
if (ds.Tables[0].Rows[0].ToString() != null)
do this
if (ds.Tables[0].Rows[0] != null) //.ToString() will cause an exception if it is actuall null
Why do I feel like I am teaching a class :)
Its because you haven't set up a handler to handle GridView.RowEditing. On your gridview (in the .aspx) you need to wire up a method which will deal with RowEditing.
You're gridview code will look like:
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
You need to add:
OnRowEditing="nameOfMethodYouWantToFire"
so it looks like:
<asp:GridView ID="GridView1" runat="server" OnRowEditing="nameOfMethodYouWantToFire">
</asp:GridView>
Where nameOfMethodYouWantToFire is in your code behind (your C#) and it handles the event. Something like this:
protected void nameOfMethodYouWantToFire(object sender, GridViewPageEventArgs e)
{
//Your code here
}

Categories