call RowDataBound from another function - c#

I have a 2 Gridviews. The first grid has a button that when clicked it will populate a second grid with the data based on the id of the button clicked.
I then have code in the RowDataBound function to show the grid based on the row selected. But the problem is the code is automatically running the RowDataBound before the populate function. So the second grid isn't displaying.
Code for GridView:
<asp:GridView style="width:75%"
ID="gvCVRT"
ShowHeaderWhenEmpty="true"
CssClass="tblResults"
runat="server"
OnRowDataBound="gvCVRT_RowDataBound"
OnSelectedIndexChanged="gridviewParent_SelectedIndexChanged"
DataKeyField="ID"
DataKeyNames="ChecklistID"
AutoGenerateColumns="false"
allowpaging="false"
AlternatingRowStyle-BackColor="#EEEEEE">
<HeaderStyle CssClass="tblResultsHeader" />
<Columns>
<asp:BoundField DataField="ChecklistID" HeaderText="ID" ></asp:BoundField>
<asp:CommandField ShowSelectButton="True" HeaderText="Select" />
<asp:BoundField DataField="ChecklistDate" HeaderText="Checklist Date" dataformatstring="{0:dd/MM/yyyy}"></asp:BoundField>
<asp:BoundField DataField="User" HeaderText="User" ></asp:BoundField>
<asp:BoundField DataField="Note" HeaderText="Note" ></asp:BoundField>
</Columns>
</asp:GridView>
Code behind:
protected void gvCVRT_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
lookupCVRT work = (lookupCVRT)e.Row.DataItem;
GridView gv = sender as GridView;
if (work.ID != null)
{
int index = gv.Columns.HeaderIndex("Select");
if (index > -1)
{
e.Row.Cells[index].Attributes.Add("class", "gvCVRTRow");
e.Row.Cells[index].ToolTip = "Click here to Edit Checklist";
}
}
}
}
Code for select button:
protected void gridviewParent_SelectedIndexChanged(object sender, EventArgs e)
{
List<lookupCVRT> workDetails = lookupCVRT.GetChecklistItemsByChecklistID(Company.Current.CompanyID, ParentID.ToString(), gvCVRT.SelectedDataKey.Value.ToString());
gvCVRTDetails.DataSource = workDetails;
gvCVRTDetails.DataBind();
FireJavascriptCallback("setArgAndPostBack ();");
}
So the problem is when I click on the Select button in the grid it runs the RowDataBound first then the gridviewParent_SelectedIndexChanged but I need to run gridviewParent_SelectedIndexChanged first. Can I call the RowDataBound function from gridviewParent_SelectedIndexChanged?
Page_Load function:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetChecklistID = "";
if (ParentID.HasValue)
{
ViewState["ParentID"] = ParentID;
List<lookupCVRT> work = lookupCVRT.GetCVRTItems(Company.Current.CompanyID, ParentID.ToString());
ViewState["CVRT"] = work;
gvCVRT.DataSource = work;
gvCVRT.DataBind();
}
}
else
{
if (ViewState["ParentID"] != null)
{
ParentID = (int?)ViewState["ParentID"];
List<lookupCVRT> work = ViewState["CVRT"] as List<lookupCVRT>;
gvCVRT.DataSource = work;
gvCVRT.DataBind();
}
}
}

The OnRowDataBound event is only called if the DataBind method for the GridView has been called.
In your specific case, the problem is in Page_Load in the else branch of the Page.IsPostBack condition:
else
{
if (ViewState["ParentID"] != null)
{
ParentID = (int?)ViewState["ParentID"];
List<lookupCVRT> work = ViewState["CVRT"] as List<lookupCVRT>;
gvCVRT.DataSource = work;
gvCVRT.DataBind();
}
}
This code is run for each postback. Unless you reset ViewState["ParentID"] somewhere else in your code, on every postback you bind the GridView gvCVRT again. This is the reason that RowDataBound is called. After finishing Page_Load, the page calls the additional event handlers, in your case gridviewParent_SelectedIndexChanged.
In order to solve this problem, you need to change the code in your Page_Load handler so that there are no calls to DataBind for a postback:
// field moved to class level so that you can access this variable instead of a DataRow in gvCVRT
private List<lookupCVRT> work;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetChecklistID = "";
if (ParentID.HasValue)
{
ViewState["ParentID"] = ParentID;
work = lookupCVRT.GetCVRTItems(Company.Current.CompanyID, ParentID.ToString());
ViewState["CVRT"] = work;
gvCVRT.DataSource = work;
gvCVRT.DataBind();
}
}
else
{
if (ViewState["ParentID"] != null)
{
ParentID = (int?)ViewState["ParentID"];
work = ViewState["CVRT"] as List<lookupCVRT>;
}
}
}
The root cause of your problem is that you need the data in a postback request and that you put these into ViewState["CVRT"] instead of requesting the data anew. In web applications it is pretty common the read the data again for a new request. So you might think about whether you really need to put the data into ViewState or whether you can request them upon a postback from the data source.
Putting the data into ViewState increases the size of the page that is transferred to the client (basically you have the HTML for the GridView and in addition you have the data in ViewState). So requesting them anew would be the better way in most cases.

I don't know why you preferred to use gridviewParent_SelectedIndexChanged then grdParent_RowDataBound ... i have created a simple solution for you .. it could help you ..
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<label>Parent Grid</label>
<asp:GridView ID="grdParent" runat="server" AutoGenerateColumns="false"
DataKeyField="Id" OnRowDataBound="grdParent_RowDataBound" OnRowCommand="grdParent_RowCommand">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:ButtonField CommandName="Details" HeaderText="Select" Text="Hello" ButtonType="Link" />
</Columns>
</asp:GridView>
</div>
<div>
<label>child Grid</label>
<asp:GridView ID="grdChild" runat="server" AutoGenerateColumns="false"
DataKeyNames="ChildId" OnRowDataBound="grdChild_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" />
<asp:BoundField DataField="Roll" />
<asp:ImageField HeaderText="Image" />
</Columns>
</asp:GridView>
</div>
</div>
</form>
</body>
</html>
Codebehind
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<ParentClass> pList = new List<ParentClass>()
{
new ParentClass{Id=5, Name="V"},
new ParentClass{Id=6,Name="VI"},
new ParentClass{Id=7,Name="VII"},
new ParentClass{Id=8,Name="VIII"},
new ParentClass{Id=9,Name="IX"},
new ParentClass{Id=10,Name="X"},
};
grdParent.DataSource = pList;
grdParent.DataBind();
}
}
protected void grdParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem == null || e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
ParentClass p = e.Row.DataItem as ParentClass;
var btn = e.Row.Cells[1].Controls[0] as LinkButton;
btn.CommandArgument = p.Id.ToString();
}
protected void grdParent_RowCommand(object sender, GridViewCommandEventArgs e)
{
int parentId = Convert.ToInt32(e.CommandArgument);
var releventStudents = GetRepositary().FindAll(i => i.ParentId == parentId);
grdChild.DataSource = releventStudents;
grdChild.DataBind();
}
protected void grdChild_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem == null || e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
//lookupCVRT work = (lookupCVRT)e.Row.DataItem;
//GridView gv = sender as GridView;
//if (work.ID != null)
//{
// int index = gv.Columns.HeaderIndex("Select");
// if (index > -1)
// {
// e.Row.Cells[index].Attributes.Add("class", "gvCVRTRow");
// e.Row.Cells[index].ToolTip = "Click here to Edit Checklist";
// }
//}
}
private List<ChildClass> GetRepositary()
{
List<ChildClass> allChild = new List<ChildClass>();
Random r = new Random();
for (int i = 0; i < 50; i++)
{
ChildClass c = new ChildClass
{
ChildId = i,
ParentId = r.Next(5, 10),
Name = "Child Name " + i,
Roll = i
};
allChild.Add(c);
}
return allChild;
}
}
public class ParentClass
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ChildClass
{
public int ParentId { get; set; }
public int ChildId { get; set; }
public int Roll { get; set; }
public string Name { get; set; }
}

Related

Disable/ Hide a control inside a specific row of GridView

I have below code to create a gridview in asp.net and inside gridview I have a delete button. Below code works fine and shows Delete in all rows.
I want to hide/ Disable the Delete button in very first row. Can somebody suggest the code part?
<asp:gridview ID="Gridview1" runat="server"
ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Cat">
<ItemTemplate>
<asp:TextBox ID="TextBoxCat" runat="server" Enabled="false"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" >
<ItemTemplate>
<asp:LinkButton ID="DeleteItemsGridRowButton" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
You can use GridView.RowDataBound Event event.
Then find the LinkButton using FindControl method.
public class Animal
{
public int RowNumber { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Gridview1.DataSource = new List<Animal>
{
new Animal {RowNumber = 1, Name = "One"},
new Animal {RowNumber = 2, Name = "Two"},
new Animal {RowNumber = 3, Name = "Three"},
new Animal {RowNumber = 4, Name = "Four"},
};
Gridview1.DataBind();
}
}
private int _counter;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (_counter == 0)
{
var linkButton = e.Row.FindControl("DeleteItemsGridRowButton")
as LinkButton;
linkButton.Visible = false;
_counter++;
}
}
}
Try This:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(GridView1.Rows.Count>0)
{
//GridView1.Rows[0].Visible = false;
LinkButton DeleteItemsGridRowButton= (LinkButton) GridView1.Rows[0].FindControl("DeleteItemsGridRowButton");
if(DeleteItemsGridRowButton!=null)
{
DeleteItemsGridRowButton.Visible=false
}
}
}

Why do checkboxes in the gridview firstly after checking and afterwards unchecking in the PreRender stage eventually are checked?

Please help me with following, just something weird is going on.
I have a gridview with paging where the first column is filled with checkboxes.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="..." DataKeyNames="EventID" EnableViewState="false"
GridLines="None" AllowSorting="True"
AllowPaging="True" Width="100%"
onpageindexchanging="GridView1_PageIndexChanging"
onprerender="GridView1_PreRender">
<HeaderStyle Wrap="false" />
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="Left">
<HeaderTemplate>
<asp:CheckBox ID="SelectAllEvs" runat="server" EnableViewState="false" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="EventSelector" runat="server" EnableViewState="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ... >
<ItemStyle Wrap="False" />
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
<asp:BoundField ... >
</asp:BoundField>
</Columns>
</asp:GridView>
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["PageIndex"] != null)
{
GridView1.PageIndex = Convert.ToInt32(Session["PageIndex"]);
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
// loading checkbox values from the session collection
GridView gv = (GridView)sender;
LoadCheckboxState(gv);
Session["PageIndex"] = gv.PageIndex;
}
private void LoadCheckboxState(GridView gv)
{
for (int i = 0; i < gv.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (SelectedIndexes.Contains(id))
{
chkBox.Checked = true;
}
else
{
chkBox.Checked = false;
}
}
}
private List<int> SelectedIndexes
{
get
{
if(Session["selectedRows"] == null)
{
Session["selectedRows"] = new List<int>();
}
return (List<int>)Session["selectedRows"];
}
}
private void SaveCheckboxState(GridView gv)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
var chkBox = GridView1.Rows[i].FindControl("EventSelector") as CheckBox;
int id = gv.PageIndex * gv.PageSize + i;
if (chkBox.Checked)
{
//see if we have an id added already
if (!SelectedIndexes.Contains(id))
{
SelectedIndexes.Add(id);
}
}
else
{
if (SelectedIndexes.Contains(id))
{
SelectedIndexes.Remove(id);
}
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
// saving current page checkbox values to the session collection
GridView gv = (GridView)sender;
SaveCheckboxState(gv);
GridView1.PageIndex = e.NewPageIndex;
}
When I first get to my page I check some checkboxes and then press F5. Apparently after pressing it I dont have any values in SelectediIndexes and all unselected checkboxes must be checked = false on the PreRender stage but they appear checked after all this. And the problem of the same nature: I checked some on the first page; went to the second page (currently having 2 indexes in the SelectedValues) and after pressing F5 the same I have checked the same checkboxes as on the first page, though they mustn't. I'm absolutely confused with this. How can I fix this? Thanx for any help.
I've found the reason to that strange behavior. I'm using Firrefox. And one of the features of this browser is saving state of some fields when refreshing the page. If you want to refresh a page fully you should refresh it with pressed shift button. Tested in Google Chrome - works just fine.

Manually updating RADGrid

I have this manually update code for my radgrid (RAD13).
on upload it works but the thing is that only the first row in the grid saves it's update.
I think that I should passe a value that will autoincrement to passe through rows
protected void UpdateButton_Click(object sender, EventArgs e)
{
RadGrid grid = (this.FindControl("RAD13") as RadGrid);
(grid.MasterTableView.GetItems(GridItemType.EditItem)[0] as GridEditableItem).FireCommandEvent(RadGrid.UpdateCommandName, string.Empty);
}
Please try with the below code snippet.
ASPX
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource"
OnUpdateCommand="RadGrid1_UpdateCommand" AllowFilteringByColumn="true" AllowPaging="true"
AllowMultiRowEdit="true">
<MasterTableView DataKeyNames="ID" EditMode="InPlace">
<Columns>
<telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
</telerik:GridBoundColumn>
<telerik:GridEditCommandColumn>
</telerik:GridEditCommandColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="update All edit row" />
ASPX.CS
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
dynamic data = new[] {
new { ID = 1, Name = "Name1"},
new { ID = 2, Name = "Name2"},
new { ID = 3, Name = "Name3"},
new { ID = 4, Name = "Name4"},
new { ID = 5, Name = "Name5"}
};
RadGrid1.DataSource = data;
}
protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
{
GridEditableItem item = e.Item as GridEditableItem;
UpdateLogic(item);
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridEditableItem item in RadGrid1.EditItems)
{
UpdateLogic(item);
item.Edit = false;
}
RadGrid1.Rebind();
}
protected void UpdateLogic(GridEditableItem item)
{
// perform your update logic here
}
Let me know if any concern.

How to temporarily store DataTable after Binding

I have two GridViews in which I populate Data on PageStart from database. When I refresh the page (on Post Back), I could not see the datatable content. so I thought of Databinding the GridView again on every pageload. In order to bind the Data I need to store the Data somewhere temporarily. Which one is the Best method to store data temporarily?
In my First Grid there are about 10 rows and in the Second GridView I have about 200 rows. and I'm not using Paging
Here's a fully working sample using ViewState but you can change it for other caching methods.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView runat="server" ID="gvProd" AutoGenerateColumns="false" OnRowDataBound="gvProd_RowDataBound" OnRowCommand="gvProd_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Literal runat="server" ID="litNm"></asp:Literal>
<asp:DropDownList runat="server" ID="ddlQty"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Add To Cart">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbnAdd" Text="Add To Cart" CommandName="AddToCart"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<hr />
<asp:GridView runat="server" ID="gvCart" AutoGenerateColumns="false" OnRowDataBound="gvCart_RowDataBound" OnRowCommand="gvCart_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="litNm"></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQty"></asp:TextBox>
<asp:Button runat="server" ID="btnUpdate" Text="Update Qty" CommandName="UpdateCart" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
[Serializable]
public class Product
{
public int PID { get; set; }
public string Name { get; set; }
public Product(int i) { this.PID = i; this.Name = "product " + i.ToString(); }
}
[Serializable]
public class CartItem
{
public Product Prod { get; set; }
public int Qty { get; set; }
public CartItem(Product p, int q) { this.Prod = p; this.Qty = q; }
}
public List<CartItem> myCart = new List<CartItem>();
public List<CartItem> MyCart
{
get
{
if (ViewState["cart"] == null)
{
ViewState["cart"] = new List<CartItem>();
}
return ViewState["cart"] as List<CartItem>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindProdGrid();
}
protected void BindProdGrid()
{
gvProd.DataSource = GetProducts();
gvProd.DataBind();
}
protected List<Product> GetProducts()
{
var ret = new List<Product>();
ret.Add(new Product(1));
ret.Add(new Product(2));
return ret;
}
protected void gvProd_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
var row = (e.CommandSource as LinkButton).NamingContainer as GridViewRow;
var ddl = row.FindControl("ddlQty") as DropDownList;
var qty = Convert.ToInt32(ddl.SelectedValue);
var pid = Convert.ToInt32(e.CommandArgument);
AddToCart(pid, qty, increase: true);
BindCartGrid(this.MyCart);
}
}
protected void AddToCart(int pid, int qty, bool increase = false)
{
var cartItem = this.MyCart.Find(o => o.Prod.PID == pid);
if (cartItem == null)
this.MyCart.Add(new CartItem(new Product(pid), qty));
else
if (increase)
cartItem.Qty += qty;
else
cartItem.Qty = qty;
}
protected void gvProd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as Product;
var litNm = e.Row.FindControl("litNm") as Literal;
litNm.Text = item.Name;
var ddlQty = e.Row.FindControl("ddlQty") as DropDownList;
ddlQty.Items.Add(new ListItem("1", "1"));
ddlQty.Items.Add(new ListItem("10", "10"));
var lbnAdd = e.Row.FindControl("lbnAdd") as LinkButton;
lbnAdd.CommandArgument = item.PID.ToString();
}
}
protected void BindCartGrid(List<CartItem> items)
{
gvCart.DataSource = items;
gvCart.DataBind();
}
protected void gvCart_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as CartItem;
var litNm = e.Row.FindControl("litNm") as Literal;
litNm.Text = item.Prod.Name + " (pid:" + item.Prod.PID.ToString() + ")";
var txtQty = e.Row.FindControl("txtQty") as TextBox;
txtQty.Text = item.Qty.ToString();
txtQty.Attributes["data-pid"] = item.Prod.PID.ToString();
}
}
protected void gvCart_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateCart")
{
var row = (e.CommandSource as Button).NamingContainer as GridViewRow;
var txtQty = row.FindControl("txtQty") as TextBox;
var qty = Convert.ToInt32(txtQty.Text);
var pid = Convert.ToInt32(txtQty.Attributes["data-pid"]);
AddToCart(pid, qty, increase: false);
BindCartGrid(this.MyCart);
}
}
}
}
Usage of Cache object vs Session again will depend upon whether you want the data to be stored temporarily per session or for all the sessions you want to store the same data.
Session can be used if you want the same data to be maintained only for a particular session of your application.
Cache can be used for all the user sessions across your application.
The best place to store the data will be sessions. Viewstate will bring all the data on client side which is an undesirable network/bandwidth overhead.
your PageStart should look like this:
public void PageStart()
{
if(Session["dt"] == null || !(Session["dt"] is datatable)){
datatable dt;
///your dt populating code
Session["dt"] = dt;
}
yourGridView.datasource = (datatable)Session["dt"];
yourGridView.databind();
}
To address data persistence between postbacks you have several options. I am really against ViewState except in very specific cases where you have a very little amount of data (that's where Microsoft fail in WebForms - its default behaviour is DemoWare).
I would suggest keeping your data in a Cache object and upon postback, read it from that object. But it really depends on your specific use case. There are different techniques.
This is all what you need to do.
Place you method or function which fills the gridview with data like this.
private void FillGrid()
{
DataTable dt = new DataTable();
dt = //Fill you datatable
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
This is what you gotta do on pageload event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.FillGrid();
}
}

How to add data to GridView?

I'm trying to add data by following code:
protected void gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Session["BranchingCode"] != null)
{
List<CourseDetail> studentList = Course_Detail.GetStudentListOfBranch(Session["BranchingCode"].ToString(), Session["CurrentSession"].ToString());
if (studentList != null)
{
for (int i = 0; i < studentList.Count(); i++)
{
e.Row.Cells[0].Text = studentList[i].UserNameRoll;
e.Row.Cells[1].Text = studentList[i].StudentName;
}
}
}
GridView1.DataBind();
}
}
But as there is no datasource attached to Gridview,This event doesn't fire.
Please tell me what to do?
Is there anyway to fire this event forcefully or do something else & enter data somewhere else..?
You misuse this event and you should not call if forcefully.
First of all somewhere in page_load event load your data and bind it to grid:
if (Session["BranchingCode"] != null)
{
List<CourseDetail> studentList = Course_Detail.GetStudentListOfBranch(Session["BranchingCode"].ToString(), Session["CurrentSession"].ToString());
if (studentList != null)
{
GridView1.DataSource = studentList;
GridView1.DataBind();
}
}
This will bind your student list to grid. Now we have to handle displaying data on grid, there are more than one ways to do that but this should be enough for you:
In your html, xxx.aspx page where you are declaring your GridView do this:
<asp:GridView ID="GridView1" runat="server" ...... >
<Columns>
<asp:BoundField HeaderText="User Name Roll" DataField="UserNameRoll" />
<asp:BoundField HeaderText="Student Name" DataField="StudentName" />
</Columns>
</asp:GridView>

Categories

Resources