grid view databound event - asp.net

how data bound event of grid view is used and how is it called could somebody elaborate a bit on this please
i bind gridview on button click like this
DataTable dt = placedStudentManager.GetPlacedStudentList(sb, passoutYear, courseList);
if (dt != null && dt.Rows.Count != 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
ViewState["dt"] = dt;
}
and whenever i need it again to bind i use view state like this, but can data bound event be any use instead of having view state can i use directly data bound event or some good alternate exist please let me know
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = (DataTable)ViewState["dt"];
GridView1.DataBind();
GridView1.Visible = true;
Btnsave.Visible = true;
// StringBuilder str=(StringBuilder)ViewState["chk"];
//foreach (GridViewRow row in GridView1.Rows)
//{
//}
}

The DataBound event fires when all the databinding for the Gridview is finished, so that you could do, say, subtotals of all the rows in the Gridview at that point as you know there aren't going to be any more rows in the view. You call it like any other event, set the attribute in your markup and put the code in your code-behind:
<asp:gridview id="Gridview1" runat="server" ondatabound="Gridview1_DataBound"
...
</asp:gridview>
private void Gridview1_DataBound(EventArgs e)
{
...
}
Could you use it in what you're doing? Possibly - can you put a bit more detail in your question about the way you're thinking?

Related

linkButton Click Event in Grid View not firing when adding though Bound Fields in a loop in GridView

Hi,Here i am trying to implement the linkButton click event in a
gridview through code behind using the BoundField Class in gridview.
when i trying to add the individual BoundField values Directly to grid
as a column in page_Load and binding the linkbutton in
RowDataBoundEvent of the row of cell with linkbutton click event, it
is firing the linkButton Click event well with the following code.
protected void Page_Load(object sender,EventArgs e)
{
BoundField bfield = new BoundField();
bfield.HeaderText = "EmpName";
bfield.DataField = "EmpName";
gridView.Columns.Add(bfield);
BoundField bfield1 = new BoundField();
bfield1.HeaderText = "Monday";
bfield1.DataField = "Monday";
gridView.Columns.Add(bfield1);
}
and in on RowDataBound Event i have wrote
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkViews = new LinkButton();
lnkViews.ID = "lnkViews";
lnkViews.Text = (e.Row.DataItem as DataRowView).Row["Monday"].ToString();
lnkViews.Click += new EventArgs(linkButton_ClickAction);
e.Row.Cells[2].Controls.Add(lnkViews);
}
}
protected void linkButton_ClickAction(object sender, EventArgs e)
{
LinkButton lnkView = (sender as LinkButton);
GridViewRow row = (lnkView.NamingContainer as GridViewRow);
string id = lnkView.CommandArgument;
string name = row.Cells[0].Text; this.ModalPopupExtender1.Show();
}
But when i trying to add the above BoundFields by looping based on the
table columns count like this, in page_Load event, the event is not
firing.
protected void Page_Load(object sender,EventArgs e)
{
DataTable dtTable = new DataTable();
dtTable= BindGrid();
BoundField boundField;
for (int i = 0; i < dtTable.Columns.Count; i++)
{
string ColumnValue = dtTable.Columns[i].ColumnName;
boundField = new BoundField();
boundField.HeaderText = ColumnValue;
boundField.DataField = ColumnValue;
gridView.Columns.Add(boundField);
}
}
when we creating the BoudnField event using the above code in a loop
based on dataSource columns count, it doesn't firing linkbutton event. why?
as per my understanding you are trying to form grid dynamically.
One thing is bound fields will not support for bubbled events. So better replace them with template fields that will meets your requirement.
You need to assign click event in InstantiateIn method by defining ITemplate interface.
OnRowDataBound event doesn't comes into picture.
below is example for your reference.
http://forums.asp.net/t/1001702.aspx

rowcommand doesnt work in first time

I have a big mistake in rowcommand. I have a button field with commandname "add". When I click it the code doesn't fire the first time but click it again and the code fires!
if (e.CommandName == "add")
{
DataClassesDataContext db = new DataClassesDataContext();
int ii = int.Parse(e.CommandArgument.ToString());
int num = int.Parse(((TextBox)GridView1.Rows[ii].FindControl("TextBox2")).Text);
string id = GridView1.Rows[ii].Cells[0].Text;
temp t = new temp();
t.tedad = num;
t.username = Session["username"].ToString();
db.temps.InsertOnSubmit(t);
db.SubmitChanges();
}
rowcommand dose not fire when clicking the first time!
You should bound the Datasource to Gridview on postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.Datasource = DataTable1;
GridView1.DataBind();
}
}
I figured out the issue, I was using GridView_RowCreated which was causing the problem, instead I used GridView_RowDataBound which solved the problem for me.
or check that if you are binding the datagrid in not post back .

Preserving CheckBox's Value in Dynamic GridView TemplateField

I am trying to create a GridView which will contain a list of users and permission levels that they have access to. Each row will have the following fields: User_ID, Username, Permission1, Permission2, ..., PermissionN, where the values of permissions field are "0" if the user does not have that permission and "1" if they do (note that columns returned by the DAL are not named Permission1, but rather are the actual name of the permission). I would like to represent the data by using CheckBoxes, to allow an admin to quickly grant or revoke permissions to a large number of users at once.
Since I will not know the number of permissions before-hand, I dynamically create TemplateFields and CheckBoxes, and this works fine; the GridView shows the current permission levels of all the users. I run into a problem when I try to update permissions based on the user checking and unchecking boxes.
Once the user is done changing permissions, I have an "Update" button, which of course causes a postback. Since the postback occurs before the OnClick event, by the time I reach OnClick all of the CheckBoxes have been reset to their initial values. Is there a way I can somehow grab the value of the CheckBoxes' Checked property before the postback occurs? Is there another (better) way of doing this? Thanks.
ASPX:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" DataKeyNames="ID">
</asp:GridView>
<asp:ObjectDataSource ID="odsUsers" runat="server" SelectMethod="GET_USERS"
TypeName="oDAL">
</asp:ObjectDataSource>
<asp:Button ID="btnUpdate" runat="server" Text="Update Permissions" OnClick="btnUpdate_OnClick"/>
Code Behind:
private static string[] excludeCols = { "ID", "Username" };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Removing the IsPostBack check refreshes the GridView when the Update button is clicked
bindGridViewWithHiddenID(gvUsers, ((DataView)odsUsers.Select()).Table, excludeCols);
}
public static bool bindGridViewWithHiddenID(GridView gv, DataTable dt, string[] excludeCols)
{
gv.Columns.Clear();
gv.DataBind();
if (gv != null && dt != null && dt.Rows.Count > 0)
{
DataControlField newField;
foreach (DataColumn column in dt.Columns)
{
if (excludeCols.Contains(column.ColumnName))
{
newField = new BoundField();
((BoundField)newField).DataField = column.ColumnName;
}
else
{
newField = new TemplateField();
((TemplateField)newField).ItemTemplate = new CustomTemplate(column.ColumnName);
}
newField.HeaderText = column.ColumnName;
if (column.ColumnName == "ID" || column.ColumnName.EndsWith("_ID"))
newField.Visible = false;
gv.Columns.Add(newField);
}
gv.DataSource = dt;
gv.DataBind();
return true;
}
return false;
}
// By this time execution reaches here the CheckBoxes have already been reset
protected void btnUpdate_Click(object sender, EventArgs e)
{
...
}
CustomTemplate class:
public class CustomTemplate : ITemplate
{
private string binding;
private static int count = 0;
public CustomTemplate(string colNameBinding)
{
binding = colNameBinding;
}
public void InstantiateIn(Control container)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + count++;
chk.DataBinding += new EventHandler(this.chk_OnDataBinding);
container.Controls.Add(chk);
}
public void chk_OnDataBinding(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow namingContainer = (GridViewRow)chk.NamingContainer;
DataRowView dataRow = (DataRowView)namingContainer.DataItem;
if (dataRow[binding].ToString() == "1")
chk.Checked = true;
else
chk.Checked = false;
}
This behavior is expected and is normal. It has to do with the Page Life cycle and tracking of ViewState on dynamically added controls. I recommend you read this article from Scott Mitchell, specially the section titled: View State and Dynamically Added Controls.
I tried adding the GridView binding to OnInit() but since the CheckBoxes aren't actually instantiated until the GridView is DataBound, and since DataBinding will revert the GridView back to its original state, I seem to be stuck again.

Code Behind Gridview's RowDataBound event

I have created a gridview in code behind (as in its not physically present on the page). I want to know how to call it's rowdatabound event - as data is being bound to it. There happens to be a Gv.RowDataBound function, but how do I use it?
(I want the same functionality as what the asp:gridview control has for its onrowdatabind attribute...)
GridView Gv = new GridView();
Gv.AutoGenerateColumns = false;
BoundField one = new BoundField();
one.DataField = "one";
one.HeaderText = "One";
Gv.Columns.Add(one);
BoundField two = new BoundField();
one.DataField = "two";
one.HeaderText = "Two";
Gv.Columns.Add(two);
//dt is a datatable with some data
Gv.DataSource = (dt);
Gv.DataBind();
Set the eventhandler for the gridview using:
Gv.RowDataBound += new GridViewRowEventHandler(Gv_RowDataBound);
Then create its own eventhandler
void Gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
//Do whatever you want in here.
}
To achieve this in VB, use this:
AddHandler Gv.RowDataBound, AddressOf Gv_RowDataBound

DataGrid Paging

I am using VB.Net 2005, with IE7.
I have a datagrid where I have set paging "AllowPaging" = True
However, when I click the link to the next page, the records are still the same.
My code is:
ds = SQLHelper.ExecuteDataset(strConn,
CommandType.StoredProcedure, "GetInventory")
dv = ds.Tables(0).DefaultView
dgInvestoryList.DataSource = dv
dgInvestoryList.DataBind()
What am I missing?
If you are using the Wizard with the SqlDataSource, then paying will be there all ready.
But if you go and place your code in the code behind you will have to do something like this - sorry i dont have the code for VB.NET - Must place code in the PageIndexChanging event. Use this This link to change my C# code to VB.NET, i use it ALOT
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
DataSet ds = new DataSet();
GridView1.DataSource = ds;
GridView1.PageIndex = e.NewPageIndex;
this.GridView1.DataBind();
}
catch (Exception)
{
Response.Redirect("Login.aspx");
}
}

Resources