nested grid control not accessible ? Null values ? problems - c#

Asp.Net Code
<asp:GridView ID="gv_current_report" runat="server" CssClass="grid" BorderStyle="Solid" BorderColor="#336699" DataKeyNames="staff_id" AutoGenerateColumns="False" GridLines="None" OnRowDataBound="gv_current_report_RowDataBound">
<AlternatingRowStyle BackColor="#DCE4F9" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="images/plus.png" width="30" />
<asp:Panel ID="detail_grid" runat="server" Style="display: none">
<asp:GridView ID="gv_detail" runat="server" AutoGenerateColumns="false" CssClass="child-grid">
<Columns>
<asp:BoundField ItemStyle-Width="150px" DataField="branch_name" HeaderText="Branch Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="date_contacted" HeaderText="Contacted Date" />
<asp:BoundField ItemStyle-Width="150px" DataField="name" HeaderText="Staff Name" />
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
C# Code
protected void gv_current_report_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Int32 staff_id = Convert.ToInt32(gv_current_report.DataKeys[e.Row.RowIndex].Value);
db = new ReportsDataContext();
gv_detail.DataSource = db.tracker_new_report_broker_status_change_current_detail(staff_id);
gv_detail.DataBind();
}
}
the problem is the panel and the grid view are not accessible in c#? If I create the controls in designer, its accessible but throwing an error
Object reference not set to an instance of an object
Found out the grid view control is NULL in run time.
( i.e.) gv_detail=Null
Anyone please shed some light. Any help will be much appreciated!!!

Related

How do I get the value of a particular row in my Gridview

I have a Gridview which also contains a button field. When this button on a particular row is clicked, I want it to update my database. For example, if a row contains (SN = 1) I want it to update the button to update the database with the row that contains "SN = 1". How do I get the SN of the row when the button on that same row is clicked?
This is my Gridview definition:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" Height="326px" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5" style="text-align: left; margin-left: 169px" Width="1069px" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:BoundField HeaderText="S/N" DataField="SN" />
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Address" DataField="Address" />
<asp:BoundField HeaderText="Phone Number" DataField="PhoneNumber" />
<asp:BoundField HeaderText="Sex" DataField="Sex" />
<asp:BoundField HeaderText="Reason" DataField="Reason" />
<asp:BoundField HeaderText="SignIn" DataField="SignIn_Time" />
<asp:BoundField HeaderText="SignOut" DataField="Signout_Time" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out" runat="server" Text="Sign out" CommandName="SignOut"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast" PageButtonCount="5" />
</asp:GridView>
Here, when the row button is clicked, I want to update my database with the signout time. I can't seem to get it to get the SN of the row and update.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{
}
}
If the value you seek is the comes from the same datasource, you can add the value as a CommandArgument:
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="out"
runat="server"
Text="Sign out"
CommandName="SignOut"
CommandArgument='<%# Eval("SN") %>'/>
</ItemTemplate>
</asp:TemplateField>
On your code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignOut")
{
string sn = e.CommandArgument.ToString();
if (sn == "1")
{
/*DO STUFF....*/
}
}
}

I would like to ask about double clicked the data Gridview row then the code below layout

HTML CODE, this concept can work , but i need to apply it on my gridview table after data binded.
$(document).ready(function () {
$('.clickme').click(function() {
alert("Hello World");
});
});
<tr class="clickme">
<td>Shop: </td>
</tr>
<asp:GridView ID="dgMain" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ChassisNo" OnPageIndexChanging="dgMain_PageIndexChanging"
OnRowCreated = "OnRowCreated" CssClass="table table-bordered" CellPadding="6" HeaderStyle-BackColor="#eeeeee" OnSorting="Sorting">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox id="chkSelection" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="No" >
<ItemTemplate>
<asp:Label id="LabelNo" runat="server" >
<%# GetIndex( DataBinder.Eval(Container, "RowIndex")) %>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="OperationName" HeaderText="Operation Name" SortExpression="OperationName"/>
<asp:BoundField DataField="OperationStart" HeaderText="Operation Start" SortExpression="OperationStart"/>
<asp:BoundField DataField="LOTNo" HeaderText="LOT No" SortExpression="LOTNo"/>
<asp:BoundField DataField="MSC" HeaderText="MSC" SortExpression="MSC" />
<asp:BoundField DataField="MaterialGroup" HeaderText="Material Group" SortExpression="MaterialGroup"/>
<asp:BoundField DataField="ChassisNo" HeaderText="Chassis No" SortExpression="ChassisNo" />
<asp:BoundField DataField="ColorID" HeaderText="Color ID" SortExpression="ColorID"/>
</Columns>
<PagerStyle HorizontalAlign="Center" />
<PagerSettings Mode="NumericFirstLast" />
</asp:GridView>
I would like to click on the row1 diagram below then will prompt out the message Hello world,
if i clicked on Row2 it will to display helloworld2.
__________________________________________________________________
|___Row1__________|_____Row1____|_______Row1_____|_____Row1________|
|___Row2__________|_____Row2____|_______Row2_____|_____Row2________|
|___Row3__________|_____Row3____|_______Row3_____|_____Row3________|
|___Row4__________|_____Row4____|_______Row4_____|_____Row4________|
If you wants to display just alert with rowNumber then it is so simple
Use
onrowdatabound="CustomersGridView_RowDataBound" for Your gridview
<asp:gridview id="CustomersGridView"
autogeneratecolumns="true"
allowpaging="true"
onrowdatabound="CustomersGridView_RowDataBound"
runat="server">
</asp:gridview>
and on Server Side
public void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "alert('helloworld " + e.Row.RowIndex + "')");
}
}

Add check box to gridview

I've a grid view with three columns Employee name Employee details and Employee age.
I want to add a check box at each row and after selection of each check box i want to fire a insert query associated to that employee.
Can you tell me how to add this dynamic functionality to the grid view.
also if we use <%# EVAL %> i don't know how to implement it with checkbox.
ASPX:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />
<asp:BoundField DataField="details" HeaderText="details"
SortExpression="details" />
<asp:BoundField DataField="age" HeaderText="age" SortExpression="age" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="OK" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connApps %>"
SelectCommand="SELECT [name], [details], [age] FROM [tblA]">
</asp:SqlDataSource>
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Selected item name:<br>";
foreach (GridViewRow item in GridView1.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("CheckBox1");
if (chk != null)
{
if (chk.Checked)
{
Label1.Text += item.Cells[1].Text + "<br>";
}
}
}
}
Output:
Here is an example ,
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="0" CellSpacing="0" DataKeyNames="CategoryID" Font-Size="10"
Font-Names="Arial" GridLines="Vertical" Width="40%">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkStatus" runat="server"
AutoPostBack="true" OnCheckedChanged="chkStatus_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("Approved")) %>'
Text='<%# Eval("Approved").ToString().Equals("True") ? " Approved " : " Not Approved " %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
<asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" Height="20" />
For more information , check Here !
you can use TemplateFields for the GridView:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:CheckBox ID="myCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and in code behind use below code:
ClusterName = GV.Rows(1).Cells(2).FindControl("myLabelinTheGridViewTemplateField")

ASP.NET Gridview ItemTemplate Access in CodeBehind

I am having trouble accessing an asp.NET HiddenField from a Gridview ItemTemplate in the codebehind. I need to be able to read the values that these hiddenfields contain so that I can execute the delete method.
The code is as follows
<%# Control Language="C#" AutoEventWireup="true" CodeFile="MemberList.ascx.cs" Inherits="UserControls_MemberList" %>
<asp:RadioButtonList ID="ReportSelect" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1">All</asp:ListItem>
<asp:ListItem Value="2">Current Members</asp:ListItem>
<asp:ListItem Value="3">Perspective Members</asp:ListItem>
</asp:RadioButtonList>
<asp:Button ID="ReportSelectButton" runat="server" OnClick="ReportSelectButton_Click"
Text="Select Report Type" />
<asp:Button ID="LinkToHomePage" runat="server" Text="Back to Homepage" OnClick="LinkToHomePage_Click">
</asp:Button>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Height="308px"
Width="1282px" onselectedindexchanged="GridView1_SelectedIndexChanged">
<Columns>
<asp:BoundField HeaderText="First Name" AccessibleHeaderText="FirstName" DataField="FirstName">
</asp:BoundField>
<asp:BoundField HeaderText="Last Name" AccessibleHeaderText="LastName" DataField="LastName">
</asp:BoundField>
<asp:BoundField HeaderText="Street Address" AccessibleHeaderText="StreetAddress"
DataField="StreetAddress"></asp:BoundField>
<asp:BoundField HeaderText="City" AccessibleHeaderText="City" DataField="City"></asp:BoundField>
<asp:BoundField HeaderText="State" AccessibleHeaderText="State" DataField="State">
</asp:BoundField>
<asp:BoundField HeaderText="Zip" AccessibleHeaderText="Zip" DataField="Zip"></asp:BoundField>
<asp:BoundField HeaderText="Birthday" AccessibleHeaderText="Birthday" DataField="Birthday" />
<asp:BoundField HeaderText="Email" AccessibleHeaderText="Email" DataField="Email">
</asp:BoundField>
<asp:BoundField HeaderText="PrimaryPhone" AccessibleHeaderText="PrimaryPhone" DataField="PrimaryPhone" />
<asp:BoundField HeaderText="AlternatePhone" AccessibleHeaderText="AlternatePhone"
DataField="AlternatePhone" />
<asp:BoundField HeaderText="Pending" AccessibleHeaderText="Pending" DataField="Pending" />
<asp:BoundField HeaderText="IsMember" AccessibleHeaderText="IsMember" DataField="IsMember" />
<asp:BoundField HeaderText="Username" AccessibleHeaderText="Username" DataField="Username">
</asp:BoundField>
<asp:BoundField HeaderText="Description" AccessibleHeaderText="Descripton" DataField="Description" />
<asp:TemplateField HeaderText="Edit" AccessibleHeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="EditUsername" runat="server" NavigateUrl='<%# Link.ToMemberAdmin(Eval("Username").ToString())%>'
Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" Text="Delete Entry" OnClick="DeleteButton_Click"/>
<asp:HiddenField ID="HiddenUsername" Value='<%#Bind("Username") %>' runat="server" />
<asp:HiddenField ID="HiddenEmail" Value='<%#Bind("Email") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind
protected void DeleteButton_Click(object sender, EventArgs e)
{
HiddenField Username = GridView1.FindControl("HidderUsername") as HiddenField;
HiddenField Email = GridView1.FindControl("HiddenEmail") as HiddenField;
string username = Username.Value;
string email = Email.Value;
AdminAccess.DeleteMemberApplication(username, email);
}
Any help would be greatly appreciated.
The HiddenField controls are going to be part of a <td> which is one of the <tr> the GridView renders. The GridView control's FindControl only knows of it's immediate children and as the Hidden controls are two levels below that, it's not going to find them. Instead, start from the sender and try to find its sibling Hidden controls. Replace the two HiddenControl lines in the event handler as below:
HiddenField Username = (HiddenField) ((Button)sender).Parent.Controls.FindControl("HiddenUsername");
HiddenField Email = (HiddenField) ((Button)sender).Parent.Controls.FindControl("HiddenEmail");
And it should get the values you are looking for to delete the data in that row.
Just use CommandArgument of button
<asp:TemplateField HeaderText="Edit" AccessibleHeaderText="Edit">
<ItemTemplate>
<asp:HyperLink ID="EditUsername" runat="server" NavigateUrl='<%# Link.ToMemberAdmin(Eval("Username").ToString())%>'
Text="Edit" />
<asp:Button ID="DeleteButton" runat="server" Text="Delete Entry" OnClick="DeleteButton_Click"
CommandArgument='<%#Eval("Username")+"^"+Eval("Email") %>'/>
</ItemTemplate>
</asp:TemplateField>
protected void DeleteButton_Click(object sender, EventArgs e)
{
var btn = sender as Button;
var args = btn.CommandArgument.Split('^');
string username = args[0];
string email = args[1];
AdminAccess.DeleteMemberApplication(username, email);
}

Nested GridView - How to trigger the Child GridView Button Click event

I need to show a Master/Child data in a page and I have used multiple GridViews to achieve the same. So, I have created two GridViews (Parent & Child) and now I want to fire the Button click event (i.e. btnLock) from the child gridview control and do some DB operations. So, I dont know how to achieve this.
Please help.
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:GridView Width="100%" AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False"
DataSourceID="sqlDsCustomers" runat="server" ShowHeader="False" OnRowCreated="gvCustomers_RowCreated">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<div class="group" id='<%#String.Format("customer{0}",Container.DataItemIndex) %>' onclick='showhide(<%#String.Format("\"#customer{0}\"",Container.DataItemIndex) %>,<%#String.Format("\"#order{0}\"",Container.DataItemIndex) %>)'>
<asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
Style="margin-right: 5px;" runat="server" /><span class="header">
<%#Eval("CustomerID")%>
:
<%#Eval("CompanyName")%>
(<%#Eval("TotalOrders")%>
Orders) </span>
</div>
<asp:SqlDataSource ID="sqlDsOrders" runat="server" ConnectionString="<%$ ConnectionStrings:Northwind %>"
SelectCommand="SELECT [OrderID], [OrderDate], [RequiredDate], [Freight], [ShippedDate] FROM [Orders] WHERE ([CustomerID] = #CustomerID)">
<SelectParameters>
<asp:Parameter Name="CustomerID" Type="String" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
<div id='<%#String.Format("order{0}",Container.DataItemIndex) %>' class="order">
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="gvOrders" DataSourceID="sqlDsOrders"
runat="server" ShowHeader="true" EnableViewState="false">
<RowStyle CssClass="row" />
<AlternatingRowStyle CssClass="altrow" />
<Columns>
<asp:TemplateField ItemStyle-CssClass="rownum">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Order ID" DataField="OrderID" ItemStyle-Width="80px" />
<asp:BoundField HeaderText="Date Ordered" DataField="OrderDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="100px" />
<asp:BoundField HeaderText="Date Required" DataField="RequiredDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="110px" />
<asp:BoundField HeaderText="Freight" DataField="Freight" DataFormatString="{0:c}"
ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Right" />
<asp:BoundField HeaderText="Date Shipped" DataField="ShippedDate" DataFormatString="{0:MM/dd/yyyy}"
ItemStyle-Width="100px" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnLock" Text="Lock" CommandName="Lock" CommandArgument=<%# Eval("OrderID") %> runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Thanks
Use the RowCommand:
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="gvOrders" DataSourceID="sqlDsOrders"
runat="server" ShowHeader="true" EnableViewState="false"
onrowcommand="gvOrders_RowCommand"
>
........
</asp:GridView >
protected void gvOrders_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Lock")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
//dowork
}
}

Categories

Resources