How to use ModalPopUpExtender in GridView? - c#

I have following tables in my database:
SuggestionsLog Table: ID, Title, Description.
Employee Table: Username, Name
Divisions Table: DivisionCode, DivisionName
I want to show table that consists of SuggestionID, SuggestionTitle, EmployeeName and DivisionName only and when the user clicks on the SuggestionTitle, a pop-up window will be displayed with the description of the suggestion.
Since I am ASP.NET beginner developer, I tried to follow this tutorial to get it but I failed.
What I did is the following:
ASP.NET Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkSuggestionTitle"
Text='<%#Eval("Title") %>'
OnClick="lnkSuggestionTitle_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />--%>
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="DivisionName" HeaderText="Division"
SortExpression="DivisionName" />
</Columns>
</asp:GridView>
<asp:Button runat="server" ID="btnModalPopUp" style="display:none" />
<AjaxToolkit:ModalPopupExtender ID="modalPopUpExtender1"
runat="server" TargetControlID="btnModalPopUp" PopupControlID="pnlPopUp" BackgroundCssClass="modalBackground"
OkControlID="btnOk" X="20" Y="100">
</AjaxToolkit:ModalPopupExtender>
<asp:Panel runat="server" ID="pnlPopUp" CssClass="confirm-dialog">
<asp:GridView ID="GridView2" runat="server">
</asp:GridView>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT dbo.SafetySuggestionsLog.ID, dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.employee.Name, dbo.SafetySuggestionsLog.Username,
dbo.Divisions.DivisionName
FROM dbo.employee INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode">
</asp:SqlDataSource>
Code-Behind:
protected void lnkSuggestionTitle_Click(object sender, EventArgs e)
{
LinkButton lnkSuggestionTitle = sender as LinkButton;
string strSuggestionTitle = lnkSuggestionTitle.Text;
string strConnectionString = ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString;
string strSelect = "SELECT ID, Title, Description FROM dbo.SafetySuggestionsLog";
SqlConnection sqlCon = new SqlConnection();
sqlCon.ConnectionString = strConnectionString;
SqlCommand cmdSuggestionDetails = new SqlCommand();
cmdSuggestionDetails.Connection = sqlCon;
cmdSuggestionDetails.CommandType = System.Data.CommandType.Text;
cmdSuggestionDetails.CommandText = strSelect;
cmdSuggestionDetails.Parameters.AddWithValue("#Title", strSuggestionTitle);
sqlCon.Open();
SqlDataReader dReader = cmdSuggestionDetails.ExecuteReader();
GridView1.DataSource = dReader;
GridView1.DataBind();
sqlCon.Close();
modalPopUpExtender1.Show();
}
Everything is going well and smooth, but in the website, when I clicked on one of the titles, I did not get the ModalPopUp. Also, I got an error notification at the left bottom corner in the Internet Explorer browser, which when I opened it, it gave me the following description:
**
Sys.ArgumentNullException: Value cannot be null. Parameter name:
elements
**
I don't know why this is happened. Any help please?

This issue is usually a bad OkControlID or CancelControlID (via here), which could be "btnOk" in this case.

Following on from #PeterX's suggestion, yes your Panel declaration is missing a lot of things.
I would redo this like something as this, which is what I use inside another even bigger GridView control.
<ajaxToolkit:ModalPopupExtender ID="mpeEndorsed" runat="server"
BackgroundCssClass="modalBackground"
PopupControlID="pnlEndorsed"
OkControlID="btnEndorsed"
CancelControlID="btnNotEndorsed"
PopupDragHandleControlID="dvHdr"
Drag="true"
TargetControlID="cbEndorsed">
</ajaxToolkit:ModalPopupExtender>
<asp:Panel ID="pnlEndorsed" runat="server" CssClass="pnlEndorsed" style="display:none">
<div id="dvHdr">
<asp:Label ID="Label3" runat="server">** CONTACT LOG **</asp:Label>
</div>
<div id="dvBody">
<table style="text-align:center; width:100%">
<tr>
<asp:GridView ID="gvContactLog" runat="server" ForeColor="#333333" GridLines="None" AllowPaging="true" PageSize="8" Font-Size="X-Small" CellPadding="4" AllowSorting="True" AutoGenerateColumns="False">
</asp:GridView>
</tr>
<tr>
<td>
<asp:Button ID="btnEndorsed" runat="server" Text="YES" />
<asp:Button ID="btnNotEndorsed" runat="server" Text="NO" />
</td>
</tr>
</table>
</div>
</asp:Panel>
Note the GridView inside the pop-up Panel is a skeleton, that has to be built up either from JavaScript or CodeBehind to get it to be useful.
Defining a Gridview in its entirety (with DataSource, fields, etc) inside a pop-up panel, that's inside another even bigger Gridview (as in my case), does not work! You will get a muddled looking screen and things all over the place. I guess it's a limitation of the AjaxToolKit, to mix client-side and server-side functionality.

Related

nested grid control not accessible ? Null values ? problems

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

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")

Refresh GridView data

In my first load of my aspx page, I have a GridView that are filled.
In my ASPX page I handle the click event on my radio button
$("#ctl00_contentConteudo_rbBuscas_1").click(function () {
$.get("../Gerenciar/ListaUsuarioProvisorio.aspx?Documentacao=s&r=" + Math.random(2), {}, function (data) {
});
});
So, this force to pass in my page load again when my radio button is clicked.
ASPX
<div id="infoGrid" runat="server">
<cc1:GridView ID="grdImoveis" CssClass="StyleGrid" Width="100%" runat="server" ShowHeader="false"
AutoGenerateColumns="False" DataSourceID="dsGrid" BorderWidth="0px" GridLines="None"
AllowPaging="True" EnableModelValidation="True" >
<AlternatingRowStyle BackColor="White" CssClass="EstiloDalinhaAlternativaGrid" HorizontalAlign="Center" />
<RowStyle CssClass="EstiloDalinhaGrid" HorizontalAlign="Center" />
<Columns>
<asp:BoundField HeaderText="Nome" DataField="NomeCompleto" />
<asp:BoundField HeaderText="Cargo" DataField="DescricaoCargo1" />
<asp:BoundField HeaderText="Data Cadastro" DataField="DataHora" />
<asp:TemplateField ControlStyle-CssClass="acoes_lista_imovel" HeaderText="Curso">
<ItemTemplate>
<div class="acoes_lista_imovel">
<%# montaIcones(Eval("Usuario_Id").ToString())%>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:GridView>
<asp:SqlDataSource ID="dsGrid" runat="server"></asp:SqlDataSource>
</div>
CODE BEHIND
In my code behind, my PageLoad just call my CarregaLista method, that fill my GridView
protected void CarregaLista()
{
string documentacao = Request.QueryString["Documentacao"].ToString();
if (documentacao.Equals("s"))
{
string select = string.Empty;
select += "SELECT top 10 San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, San_Usuario.DescricaoCargo1, "
+ "CONVERT(varchar, San_Usuario.DataHora, 103) AS DataHora "
+ "FROM San_Usuario "
+ "JOIN San_Credenciada "
+ "ON San_Usuario.Credenciada_Id = San_Credenciada.Credenciada_Id "
+ "WHERE San_Usuario.Excluido = 0 "
+ "GROUP BY San_Credenciada.Apelido, San_Usuario.NomeCompleto, San_Usuario.Usuario_Id, "
+ "San_Usuario.DescricaoCargo1, San_Usuario.DataHora "
+ "ORDER BY San_Usuario.DataHora ASC ";
dsGrid.ConnectionString = c.Con;
dsGrid.SelectCommand = select;
dsGrid.DataBind();
grdImoveis.DataBind();
dsGrid.Dispose();
}
}
}
WITH UPDATE PANEL
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
<asp:RadioButton ID="RadioButton2" runat="server" Text="Curso Básico Netimóveis" />
<asp:RadioButton ID="RadioButton1" runat="server" Text="Buscar Lista de Presença" />
<asp:RadioButton ID="rdBuscas" runat="server" OnCheckedChanged="Click" Text="Curso Documentação Imobiliária" />
<cc1:GridView ID="grdImoveis" CssClass="StyleGrid" Width="100%" runat="server" ShowHeader="false"
AutoGenerateColumns="False" DataSourceID="dsGrid" BorderWidth="0px" GridLines="None"
AllowPaging="True" EnableModelValidation="True" >
<AlternatingRowStyle BackColor="White" CssClass="EstiloDalinhaAlternativaGrid" HorizontalAlign="Center" />
<RowStyle CssClass="EstiloDalinhaGrid" HorizontalAlign="Center" />
<Columns>
<asp:BoundField HeaderText="Nome" DataField="NomeCompleto" />
<asp:BoundField HeaderText="Cargo" DataField="DescricaoCargo1" />
<asp:BoundField HeaderText="Data Cadastro" DataField="DataHora" />
<asp:TemplateField ControlStyle-CssClass="acoes_lista_imovel" HeaderText="Curso">
<ItemTemplate>
<div class="acoes_lista_imovel">
<%# montaIcones(Eval("Usuario_Id").ToString())%>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</cc1:GridView>
<asp:SqlDataSource ID="dsGrid" runat="server"></asp:SqlDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rdBuscas" />
</Triggers>
</asp:UpdatePanel>
My problem is that my GridView don't refresh with this query.
How can I solve this ?
You can use Ajax Tretament - based on UpdatePanel, Triggers and UpdateMode="Condition"
You can use this code (Adjust your GridView and Id of your radio button on trigger)
<asp:ScriptManager ID="ScriptManager1" runat="server" >
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" ModeUpdate="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server">
<Columns>
......
</Columns>
</asp:GridView>
<asp:RadioButton ...../>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="YourRadioButtonId" EventName="Click" />
</Triggers>
</asp:UpdatePanel>

How to let this DropDownList (filter) works again with this GridView?

I am developing an intranet web application which works as a Suggstions Box. The Admin will see a list of all submitted suggestions in a GridView and he has the ability to accept or reject these suggestions through the DropDownList that is added to the GridView. Besides that, there is a DropDownList at the top of this GridView to filter the suggestions based on the Division of the user who submitted one of these suggestions.
In addition, under this GridView, there is another GridView that shows the suggestions with their status as Accepted or Rejected. This GridView will be refreshed immediately after each time the admin accepts or rejects one of the suggestions. Also, the Admin has the ability to print this GridView.
Everything was working fine before adding the second GridView inside the UpdatePanel control, but now the filter for filtering the suggestions in the first GridView is not working. Any idea? Any help please?
My ASP.NET Code:
<strong> Division </strong>
<asp:DropDownList ID="ddlDivision" runat="server" AppendDataBoundItems="True"
AutoPostBack="True" DataSourceID="sqlDataSourceDivision" DataTextField="DivisionShortcut"
DataValueField="DivisionShortcut"
Width="175px" EnableViewState="False">
<asp:ListItem Value="%">All</asp:ListItem>
</asp:DropDownList>
<br /> <br />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ID"
width="950px" CssClass="mGrid"
AlternatingRowStyle-CssClass="alt"
RowStyle-HorizontalAlign="Center"
DataSourceID="SqlDataSource1"
OnRowDataBound="GridView1_RowDataBound" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold = "true" ForeColor="Black" Height="20px"/>
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Username" HeaderText="Username"
SortExpression="Username" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:DropDownList ID="DropDownList" runat="server" DataSourceID="SqlDataSource2"
Font-Bold="True" ForeColor="#006666" AppendDataBoundItems="false"
DataTextField="Status" DataValueField="ID" AutoPostBack="true"
OnDataBound="DropDownList_DataBound" OnSelectedIndexChanged ="DropDownList_SelectedIndexChanged">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT dbo.SafetySuggestionsLog.ID, dbo.SafetySuggestionsLog.Title, dbo.SafetySuggestionsLog.Description, dbo.employee.Name, dbo.SafetySuggestionsLog.Username,
dbo.Divisions.DivisionShortcut
FROM dbo.employee INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.Divisions ON dbo.employee.DivisionCode = dbo.Divisions.SapCode"
FilterExpression="[DivisionShortcut] like '{0}%'">
<FilterParameters>
<asp:ControlParameter ControlID="ddlDivision" Name="DivisionShortcut"
PropertyName="SelectedValue" Type="String" />
</FilterParameters>
</asp:SqlDataSource>
<%--For the DropDownList--%>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT * FROM [SafetySuggestionsStatus]">
</asp:SqlDataSource>
<%--Filtering by Division--%>
<asp:SqlDataSource ID="sqlDataSourceDivision" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>"
SelectCommand="SELECT [DivisionShortcut] FROM [Divisions]"></asp:SqlDataSource>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlDivision" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<br />
<p><h3><b><u>PMOD Divisions' Safety Suggestions List</u></b></h3>
<p>
</p>
<br />
<asp:Panel ID="Panel1" runat="server">
<asp:GridView ID="GridView2" runat="server" AllowSorting="True"
AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="False" CssClass="mGrid"
DataSourceID="SqlDataSource4" RowStyle-HorizontalAlign="Center">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<HeaderStyle Font-Bold="true" ForeColor="Black" Height="20px" />
<Columns>
<asp:BoundField DataField="SubmittedMonth" HeaderText="Month Submitted"
ReadOnly="True" SortExpression="SubmittedMonth" />
<asp:BoundField DataField="DivisionShortcut" HeaderText="Division"
SortExpression="DivisionShortcut" />
<asp:BoundField DataField="Username" HeaderText="NetworkID"
SortExpression="Username" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
</Columns>
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
</asp:Panel>
<asp:SqlDataSource ID="SqlDataSource4" runat="server"
ConnectionString="<%$ ConnectionStrings:testConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT LEFT(DATENAME(month, dbo.SafetySuggestionsLog.DateSubmitted), 3) + '-' + DATENAME(year, dbo.SafetySuggestionsLog.DateSubmitted)
AS SubmittedMonth, dbo.Divisions.DivisionShortcut, dbo.SafetySuggestionsLog.Username, dbo.employee.Name, dbo.SafetySuggestionsLog.Title,
dbo.SafetySuggestionsLog.Description, dbo.SafetySuggestionsType.Type, dbo.SafetySuggestionsStatus.Status
FROM dbo.Divisions INNER JOIN
dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
dbo.SafetySuggestionsLog ON dbo.employee.Username = dbo.SafetySuggestionsLog.Username INNER JOIN
dbo.SafetySuggestionsType ON dbo.SafetySuggestionsLog.TypeID = dbo.SafetySuggestionsType.ID INNER JOIN
dbo.SafetySuggestionsStatus ON dbo.SafetySuggestionsLog.StatusID = dbo.SafetySuggestionsStatus.ID
WHERE (DATEDIFF(month, dbo.SafetySuggestionsLog.DateSubmitted, GETDATE()) < 3)
ORDER BY dbo.SafetySuggestionsLog.DateSubmitted DESC"></asp:SqlDataSource>
<asp:Button ID="btnPrint" runat="server" OnClick="btnPrint_Click"
Text="Print" />
<p>
</p>
</p>
</ContentTemplate>
</asp:UpdatePanel>
Code-Behind:
protected void btnPrint_Click(object sender, EventArgs e)
{
Session["ctrl"] = Panel1;
ScriptManager.RegisterStartupScript(GridView2, GridView2.GetType(), "onclick", "window.open('Print.aspx','PrintMe','height=400px,width=800px,scrollbars=1');", true);
}
int i = 1;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = i.ToString();
i++;
}
}
protected void DropDownList_DataBound(object sender, EventArgs e)
{
if (!IsPostBack)
{
((DropDownList)sender).Items.Insert(0, new ListItem("--Select--", ""));
}
}
protected void DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
int suggestionStatus = int.Parse(ddl.SelectedValue);
GridViewRow row = (GridViewRow)ddl.NamingContainer;
string strID = GridView1.DataKeys[row.RowIndex]["ID"].ToString();
int ID = Int32.Parse(strID);
//For inserting the status in the database
string connString = "Data Source=localhost\\sqlexpress;Initial Catalog=psspdbTest;Integrated Security=True";
string updateCommand = "UPDATE SafetySuggestionsLog SET [StatusID] = #StatusID WHERE [ID] = #ID";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#StatusID", suggestionStatus);
cmd.Parameters.AddWithValue("#ID", ID);
cmd.ExecuteNonQuery();
}
conn.Close();
}
GridView2.DataBind();
}
Can you specify what is the id for the 1st grid?
What I can conceive is that maybe you are not updating the updatepanel manually on your selectedIndex change event
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(updateCommand, conn))
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#StatusID", suggestionStatus);
cmd.Parameters.AddWithValue("#ID", ID);
conn.Open();
cmd.ExecuteNonQuery();
}
conn.Close();
}
GridView2.DataBind();
UpdatePanel1.Update();
Also in your aspx set UpdateMode="Conditional"
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">

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