I have code to have a dynamic button appear after it does an if else loop for checking for some data.
however, the gridview cant do any paging. it only shows the first page and cant go to 2nd page and so on.
It only can do the paging IF i nvr call the method below.
here is my code
public void filter_select(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
........
}
that method will be called on the rowdatabound gridview page source like this OnRowDataBound="filter_select"
my gridview code on source code is :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" CellPadding="2" CellSpacing="2"
HorizontalAlign="Center" OnRowCommand="stop_survey"
OnRowDataBound="filter_select" OnSelectedIndexChanging="selected" PageSize="5"
Width="133%" DataKeyNames="SurveyID" DataSourceID="SqlDataSource1" AutoGenerateColumns="False"
>
<Columns>
<asp:BoundField DataField="SurveyID" HeaderText="Survey ID" ReadOnly="True"
.........
my onrowCommand code
public void stop_survey(object sender, GridViewCommandEventArgs e)
{
SqlConnection con;
string sqlcom;
SqlCommand cmd;
//is it because of this code below? as if i comment from this code onwards, the paging works.
GridViewRow row = (GridViewRow)((Button)e.CommandSource).NamingContainer;
Button btn = (Button)GridView1.Rows[row.RowIndex].FindControl("btnStop");
...............
Rebind your gridview in the PageIndexChanging event of the gridview control
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = DataAcceessLayer.GetEmployeeData();
GridView1.DataBind();
}
Related
I have a label in an asp GridView and I want to set bind data to it.
Here is my RowDataBound method:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
var name = (Label)e.Row.FindControl("Label_name");
name.Text ="sara";
name.DataBind();
}
and here is my GridView:
<asp:GridView ID="GridViewCertificateType" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView1_RowDataBound" >
<asp:Label ID="Label_name" runat="server" Text="" ></asp:Label>
But after name.Text ="sara";, I receive this exception:
Object reference not set to an instance of an object.
In your RowDataBound method, make sure you have a condition to check what the type of the row is. This event will be called for every row in your GridView, including header and footer rows. If Label_name is not found in the header row, you'll have a null object. Once you do that, get rid of name.DataBind();, as it is not needed.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var name = (Label)e.Row.FindControl("Label_name");
name.Text = "sara";
}
}
try this
var name= (Label)e.Row.Cells[X].FindControl("Label_name");
name.Text ="sara";
name.DataBind();
X means index of column
I have a checkbox in my gridview footer with autopostack=true (which should fire a checkedchanged event), and a linkbutton in my itemtemplate (which should fire the gridview rowcommand event).
Everything has been working fine, until I placed the following code in my gridview rowdatabound (or databound) event:
for (int i = 0; i < gridCartRows.Columns.Count - 2; i++)
{
e.Row.Cells.RemoveAt(0);
}
e.Row.Cells[0].ColumnSpan = gridCartRows.Columns.Count - 1;
Now, when I click my linkbutton, the checkbox checkedchanged event is automatically fired, and then the rowcommand event is fired.
Why is the checkedchanged event being fired when it shouldn't, when I add the above code?
Is there a way to get around this?
Edit
Here's a sample, that reproduces my issue:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="True"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Column1">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column2">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text="Fire Row Command" CommandName="Fire" />
</ItemTemplate>
<FooterTemplate>
Footer
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="true" OnCheckedChanged="CheckBox1_CheckedChanged" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Column3">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = new int[5];
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
for (int i = 0; i < GridView1.Columns.Count - 2; i++)
{
e.Row.Cells.RemoveAt(0);
}
e.Row.Cells[0].ColumnSpan = GridView1.Columns.Count - 1;
((CheckBox)e.Row.FindControl("CheckBox1")).Checked = true;
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Fire")
{
Response.Write("RowCommand fired.");
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
Response.Write("CheckBox fired.");
}
Note, I'm setting the CheckBox property to true in the RowDataBound - if I remove this, it works fine. So merging the cells and setting the checkbox property aren't working nicely together.
GridView Control events are stored in viewstate and they can get messed up very easily. Here removing a cell causing to bind different event to link button. Although after postback __EVENTTARGET is LinkButton, wrong method is called and wrong control, event arguments are passed.
I would suggest to hide the cell rather than removing it:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
e.Row.Cells[1].ColumnSpan = GridView1.Columns.Count - 1;
e.Row.Cells[0].Visible = false;
((CheckBox)e.Row.FindControl("CheckBox1")).Checked = true;
}
}
This will serve the purpose.
I am using a gridview fed from a SQL database. I need to add a custom itemTemplate that will consist of a checkboxlist fed from another datasource. Here is my xml part :
<asp:TemplateField HeaderText="Equipements" >
<EditItemTemplate>
<asp:CheckBoxList ID="myCB" runat="server">
</asp:CheckBoxList>
</EditItemTemplate>
</asp:TemplateField>
I am using the gridview onEditing event to try to access "myCB" in the code behind :
protected void OnEditing(object sender, EventArgs e)
{
GridView gridview = sender as GridView;
GridViewEditEventArgs editEvent = e as GridViewEditEventArgs;
ListViewItemEventArgs rowEvent = e as ListViewItemEventArgs;
TableCell equipementsCell = gridview.Rows[editEvent.NewEditIndex].Cells[11];
CheckBoxList equipements = gridview.Rows.FindControl("myCB") as CheckBoxList;
}
This code doesn't work, the checkboxlist isn't found. I have tried many things unsuccessfully...
You should use GridView's RowDataBound event:
protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow
&& e.Row.RowState == DataControlRowState.Edit)
{
CheckBoxList equipements = (CheckBoxList )e.Row.FindControl("myCB");
equipements.DataSource = getSomeData();
equipements.DataTextField = "TextColumn";
equipements.DataTextField = "IdColumn";
equipements.DataBind();
}
}
i'm am pulling 10 out of 100 records back from the database and placing into gridview (no datasource objects here).
how do i enable paging that comes with the gridview? I know the total records is 100 can I use that somehow to activate the paging?
I know I can do this easily with DataSource objects but was just wondering if I could do it completely manually as far as the GridView is concerned.
Markup
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" onpageindexchanging="GridView1_PageIndexChanging"
onsorting="GridView1_Sorting">
</asp:GridView>
</div>
</form>
Code-behind
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetCustomers();
GridView1.DataBind();
}
strong text
Try this:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback) {BindData();}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.DataSource = GetCustomers();
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
void BindData()
{
GridView1.DataSource = GetCustomers();
GridView1.DataBind();
}
Also you need to add this to gridview markup:
OnPageIndexChanging="GridView1_PageIndexChanging"
I have a gridview in which every row contains a dropdownlist. I want to bind every dropdownlist dynamically. Can someone tell me how can i do it. Thanks in Advance
If you are using template column then you can bind your drop-down from mark-up using data-binding expressions. For example,
<asp:TemplateField HeaderText="XYZ">
<ItemTemplate>
<asp:DropDownList runat="server" ID="MyDD" DataSourceId="MyDataSource" />
</ItemTemplate>
</asp:TemplateField>
Above is assuming that your drop-down data in constant across rows. If it is changing then you can use data-binding expression such as
<asp:DropDownList runat="server" DataSource='<%# GetDropDownData(Container) %>' DataTextField="Text" DataValueField="Value" />
GetDropDownData will be a protected method in code-behind that will return the data (data-table, list, array) for the given row.
You can use GridView.RowDataBound event (or RowCreated event) in code-behind to fill drop-downs. For example,
protected void GridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Find the drop-down (say in 3rd column)
var dd = e.Row.Cells[2].Controls[0] as DropDownList;
if (null != dd) {
// bind it
}
/*
// In case of template fields, use FindControl
dd = e.Row.Cells[2].FindControl("MyDD") as DropDownList;
*/
}
}
In addition to the proposed methods, you may also bind your controls within your markup, in this way:
<asp:GridView ID="MyGrid" runat="server" DataSourceID="MyDataSource1">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind ("CustomerId") %>' DataSourceID="CustomersDataSource" DataTextField="CustomerName" DataValueField="CustomerId" >
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is your gridview
<asp:GridView ID="grvExcelData" runat="server" onrowdatabound="GridView2_RowDataBound">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DrdDatabase" Width="100px" runat="server">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and your RowDataBound event for the gridview would be
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
string cities = "maxico,chennai,newdelhi,hongkong";
string [] arr = cities.Split(',');
// Instead of string array it could be your data retrieved from database.
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DrdDatabase");
foreach (string colName in arr )
ddl.Items.Add(new ListItem(colName));
}
}
protected void gvSalesAppData_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlCurrentPhase = (DropDownList)e.Row.FindControl("ddlCurrentPhase");
DropDownList ddlProductFamily = (DropDownList)e.Row.FindControl("ddlProductFamily");
DropDownList ddlProductGroup = (DropDownList)e.Row.FindControl("ddlProductGroup");
DropDownList ddlETProgramManager = (DropDownList)e.Row.FindControl("ddlETProgramManager");
DropDownList ddlPLMForTheProduct = (DropDownList)e.Row.FindControl("ddlPLMForTheProduct");
TrackingToolObj.BindCurrentPhases(ddlCurrentPhase);
TrackingToolObj.BindCurrentPhases(ddlProductFamily);
TrackingToolObj.BindProductGroups(ddlProductGroup);
TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlETProgramManager, (int)OSAEnums.RoleTypes.ProgramManager, false);
TrackingToolObj.GetEmployeesBasedOnRoleTypeId(ddlPLMForTheProduct, (int)OSAEnums.RoleTypes.PLM, false);
}
}
Binding the GridView
Below is the code to Bind the GridView control with data.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
string query = "SELECT top 10 * FROM Customers";
SqlCommand cmd = new SqlCommand(query);
gvCustomers.DataSource = GetData(cmd);
gvCustomers.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}