I have follow your article http://www.aspforums.net/Threads/754635/How-to-keep -Nested-Child-GridViews-Expanded-across-PostBack-in-ASPNet/
In my child grid i have one checkbox IsReviewed and one update button outside grid but prob is that suppose i checked Isreviewed checkbox and then click on update button ,so value of Isreviwed checkbox is going 1 which is fine but after clicked update and page is postback ,now i am again uncheck Isreviewed checkbox then click on update button this checkbox value always going 1 which is prob in this code. so pls give me solution for this prob afterpostback page if i uncheck Isreviewed checkbox value should go 0.
namespace ParkMedicalBilling
{
public partial class PatientStatementManagment : NumerousUMS.Common.BasePage
{
NumerousUMSDataContext db = new NumerousUMSDataContext();
string Sort_Direction = "LastUpdatedTime DESC";
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constring"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnUpdate.Visible = false;
lblRowsCount.Visible = false;
btnDelete.Visible = false;
ViewState["SortExpr"] = Sort_Direction;
BindClients();
GetParentList();
}
// For Re Exapnding the expanded rows
foreach (GridViewRow row in gvPatientParent.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
HiddenField IsExpanded = row.FindControl("IsExpanded") as HiddenField;
IsExpanded.Value = Request.Form[IsExpanded.UniqueID];
}
}
}
protected void BindClients()
{
try
{
lblmessage.Text = "";
Utility.PopulateRoleList(DateTime.Now, db, ddlClients, Session[Constants.ParentRoleId], Session[Constants.SiClientMappingId], Session[Constants.UserID], "0");
}
catch (Exception ex)
{
lblmessage.Text = "<b>Error Message: </b>" + ex.Message;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
lblTotalAmount.Text = string.Empty;
btnUpdate.Visible = false;
lblRowsCount.Visible = false;
btnDelete.Visible = false;
// BindCoPayFltrMsg();
GetParentList();
}
public void GetParentList()
{
int clientid = 0;
int patientid = 0;
int.TryParse(ddlClients.SelectedValue, out clientid);
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constring"].ConnectionString))
{
string sSQL = "Exec [get_ListOfPatientStatementStatus] @ClientId=" + clientid + ", @PatientId='" + patientid + "'";
DataTable dt = GetData(sSQL);
if (dt.Rows.Count > 0)
{
gvPatientParent.DataSource = dt;
gvPatientParent.DataBind();
lblRowsCount.Text = "No.Of Patients: " + dt.Rows.Count;
ltrlPageView.Text = "You are viewing page " + gvPatientParent.PageIndex + 1 + " of " + gvPatientParent.PageCount;
lblmessage.Text = "";
}
else
{
lblmessage.Text = "No records found!!!";
gvPatientParent.DataSource = null;
gvPatientParent.DataBind();
}
//sSQL = "select SUM(Amount) As TotalAmount from dbo.BCBS Where IsPaid = 0 and si_ClientID = " + clientid;
sSQL = "select SUM(PatientResponsibility) As TotalAmount from dbo.PatientStatementManagement Where si_clientid = " + clientid;
dt = GetData(sSQL);
string totalAmount = "0";
if (dt != null && dt.Rows.Count > 0)
{
totalAmount = Convert.ToString(dt.Rows[0][0]);
if (!string.IsNullOrWhiteSpace(totalAmount))
{
totalAmount = Convert.ToString(Convert.ToDouble(totalAmount));
}
}
if (!string.IsNullOrWhiteSpace(totalAmount))
{
if ((string)Session[Constants.RoleID] == "49")
{
lblTotalAmount.Visible = false;
}
else
{
Decimal decimalAmount = Convert.ToDecimal(totalAmount);
//lblTotalAmount.Text = "Total Amount: " + string.Format("{0:c}", decimalAmount);
lblTotalAmount.Text = "Total Amount: " + decimalAmount.ToString("C");
}
}
gvPatientParent.Visible = (gvPatientParent.Rows.Count > 0);
}
}
protected string UpdatePatient(string ID, bool IsReviewed = false)
{
string sValue = "";
// define connection and command, in using blocks to ensure disposal
using (SqlCommand cmd = new SqlCommand("dbo.get_ListOfPatientStatementStatus_Update", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("@ID", SqlDbType.Int);
cmd.Parameters.Add("@IsReviewd", SqlDbType.Bit);
cmd.Parameters.Add("@ApplicationMsg", SqlDbType.NVarChar, 4000).Direction = ParameterDirection.Output;
// set parameter values
cmd.Parameters["@ID"].Value = ID;
cmd.Parameters["@IsReviewd"].Value = IsReviewed;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from @NewId
sValue = Convert.ToString(cmd.Parameters["@ApplicationMsg"].Value);
if (conn.State == ConnectionState.Open)
conn.Close();
}
return sValue;
}
private void BindChildGrid(GridView gvList, string ID)
{
try
{
lblmessage.Text = "";
// string sSQl = "EXECUTE [ums].[sp_GetBCBsData] ";
string sSQl = "EXECUTE [get_ListOfPatientStatementStatus_Detail] ";
if (ddlClients.SelectedValue != "")
{
sSQl += " " + Convert.ToInt32(ddlClients.SelectedValue);
if (!string.IsNullOrWhiteSpace(ID))
sSQl += "," + Convert.ToInt32(ID);
}
SqlCommand cmd = new SqlCommand(sSQl);
DataTable dt = GetData(sSQl);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
gvList.DataSource = dt;
gvList.DataBind();
lblRowsCount.Text = "Total Rows: " + dt.Rows.Count;
ltrlPageView.Text = "You are viewing page " + gvList.PageIndex + 1 + " of " + gvList.PageCount;
lblmessage.Text = "";
}
else
{
lblmessage.Text = "No records found!!!";
gvList.DataSource = null;
gvList.DataBind();
}
gvList.Visible = (gvList.Rows.Count > 0);
btnUpdate.Visible = (gvList.Rows.Count > 0);
btnDelete.Visible = (gvList.Rows.Count > 0);
lblRowsCount.Visible = (gvList.Rows.Count > 0);
ltrlPageView.Visible = (gvList.Rows.Count > 0);
}
else
{
lblmessage.Text = "No records found!!!";
}
}
catch (Exception ex)
{
lblmessage.Text = "<b>Error Message: </b>" + ex.Message;
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
}
protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
{
lblmessage.Text = "";
gvPatientParent.PageIndex = e.NewPageIndex;
GetParentList();
}
protected void Sorting(object sender, GridViewSortEventArgs e)
{
string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
if (SortOrder[0] == e.SortExpression)
{
if (SortOrder[1] == "ASC")
{
ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
}
else
{
ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
}
}
else
{
ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
}
GetParentList();
}
private DataTable ExecuteQuery(SqlCommand cmd, string action)
{
string conString = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
cmd.Connection = con;
switch (action)
{
case "SELECT":
using (SqlDataAdapter sda = new SqlDataAdapter())
{
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
case "UPDATE":
con.Open();
cmd.ExecuteNonQuery();
con.Close();
break;
}
return null;
}
}
protected void btnUpdate_Click1(object sender, EventArgs e)
{
lblmessage.Text = "";
string sMsg = "";
try
{
foreach (GridViewRow parentRow in gvPatientParent.Rows)
{
GridView gvList = parentRow.Cells[0].Controls[1].Controls[1] as GridView;
foreach (GridViewRow row in gvList.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
bool isChecked = row.Cells[0].Controls.OfType<CheckBox>().FirstOrDefault().Checked;
if (isChecked)
{
sMsg = UpdatePatient(Convert.ToString(gvList.DataKeys[row.RowIndex].Value),
row.Cells[5].Controls.OfType<CheckBox>().FirstOrDefault().Checked
);
}
}
}
}
//btnUpdate.Visible = false;
GetParentList();
foreach (GridViewRow row in gvPatientParent.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
HiddenField IsExpanded = row.FindControl("IsExpanded") as HiddenField;
IsExpanded.Value = Request.Form[IsExpanded.UniqueID];
}
}
if (sMsg != "")
lblmessage.Text = "<b>Message: </b>" + sMsg + "<br /><br />";
lblmessage.Attributes["style"] = "color:green; font-weight:bold;";
// ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record(s) are updated sucessfully!!!')", true);
}
catch (Exception ex)
{
lblmessage.Text = "<b>Error Message: </b>" + ex.Message + "<br /><br />";
lblmessage.Attributes["style"] = "color:red; font-weight:bold;";
}
}
protected void gvPatientParent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string customerId = gvPatientParent.DataKeys[e.Row.RowIndex].Value.ToString();
GridView gvList = e.Row.FindControl("gvList") as GridView;
BindChildGrid(gvList, customerId);
}
}
private static DataTable GetData(string query)
{
string strConnString = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = query;
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.CommandTimeout = 0;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
}
}
}
}
}
<%@ Page Title="Park Medical Billing - Welcome" Language="C#" MasterPageFile="~/Site.Master"
AutoEventWireup="true" Inherits="ParkMedicalBilling.PatientStatementManagment" CodeBehind="PatientStatementManagment.aspx.cs" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<script type="text/javascript" src="/js/jQuery%201.8.1/jquery.min.js"></script>
<script type="text/javascript">
var TotalChkBx;
var Counter;
window.onload = function () {
//Get total no. of CheckBoxes in side the GridView.
TotalChkBx = parseInt('<%= this.gvPatientParent.Rows.Count %>');
//Get total no. of checked CheckBoxes in side the GridView.
Counter = 0;
}
function HeaderClick(CheckBox) {
//Get target base & child control.ss
var TargetBaseControl = $(CheckBox).closest('table');
var TargetChildControl = "chkBxSelect";
//Get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.find("input");
//Checked/Unchecked all the checkBoxes in side the GridView.
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
Inputs[n].checked = CheckBox.checked;
//Reset Counter
Counter = CheckBox.checked ? TotalChkBx : 0;
}
function ChildClick(CheckBox, HCheckBox) {
//get target control.
var HeaderCheckBox = document.getElementById(HCheckBox);
//Modifiy Counter;
if (CheckBox.checked && Counter < TotalChkBx)
Counter++;
else if (Counter > 0)
Counter--;
//Change state of the header CheckBox.
if (Counter < TotalChkBx)
HeaderCheckBox.checked = false;
else if (Counter == TotalChkBx)
HeaderCheckBox.checked = true;
}
</script>
<script type="text/javascript">
function MarckCheck(textarea) {
var id = textarea.split('_');
if ($('#MainContent_gvPatientParent_gvList_' + id[3] + '_chkBxSelect_' + id[5]).is(':checked') == true) { return; }
//MainContent_gvPatientParent_gvList_2_chkBxSelect_0
$(' #MainContent_gvPatientParent_gvList_' + id[3] + '_chkBxSelect_' + id[5]).attr('checked', 'checked');
}
$("[src*=plus]").live("click", function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
$(this).next().html('');
$(this).attr("src", "/images/minus.png");
// $("[id=IsExpanded]").val("1");
$(this).next().next().val("1");
});
$("[src*=minus]").live("click", function () {
$(this).attr("src", "/images/plus.png");
$(this).next().html($(this).closest("tr").next().children().eq(1).html());
$(this).closest("tr").next().remove();
// $("#IsExpanded").val("");
$(this).next().next().val("");
});
$("[src*=Expand]").live("click", function () {
$("[src*=plus]").click();
$(this).attr("src", "/images/collapse.png");
});
$("[src*=collapse]").live("click", function () {
$("[src*=minus]").click();
$(this).attr("src", "/images/Expand.png");
});
function AddUpdateMasterRoleCallBack(selectedValue) {
$('#MainContent_ddlClients').val(selectedValue).change();
}
$(function () {
$("[id*=IsExpanded]").each(function () {
if ($(this).val() == "1") {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $("[id*=pnlOrders]", $(this).closest("tr")).html() + "</td></tr>")
$("[src*=plus]", $(this).closest("tr")).attr("src", "/images/minus.png");
}
});
})
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div id="title-breadcrumb-demo" class="page-title-breadcrumb">
<div class="page-header pull-left">
<div class="page-title">
<asp:Literal ID="ltrPageTitle" Text="Patient Statement Management" runat="server" />
</div>
</div>
<div class="clearfix">
</div>
</div>
<table cellpadding="1" class="centreAlignment" cellspacing="1" border="0" width="100%">
<tr>
<td colspan="6">
</td>
</tr>
<tr style="display: none;">
<td valign="top" class="auto-style1">
<b>Select Clients :</b>
</td>
<td align="left" width="7%">
<asp:DropDownList ID="ddlClients" Enabled="true" runat="server" Width="210px" AutoPostBack="true" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>
</td>
<td align="left" width="7%"></td>
<td align="left" width="7%"></td>
<td align="left" width="7%"></td>
<td></td>
</tr>
<tr>
<td colspan="6" width="100%" align="center" valign="top">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td width="100%" align="center" colspan="3">
<asp:Label ID="lblmessage" runat="server" ClientIDMode="AutoID"></asp:Label>
</td>
</tr>
<tr>
<td align="left">
<asp:Label ID="lblRowsCount" Font-Size="Small" Font-Bold="true" runat="server"></asp:Label>
<asp:Label ID="lblTotalAmount" Font-Size="Small" Font-Bold="true" Style="padding-left: 15px;" runat="server"></asp:Label>
<asp:Button ID="btnUpdate" runat="server" CssClass="btn btn-primary blue dropdown-toggle" Text="Update" OnClick="btnUpdate_Click1" CausesValidation="False" ClientIDMode="AutoID" />
</td>
<td align="center">
<div style="color: Green; font-weight: bold; display: none;">
<i>
<asp:Label ID="ltrlPageView" runat="server"></asp:Label>
</i>
</div>
</td>
<td align="left" class="marginBottom">
<asp:Button ID="btnDelete" runat="server" Style="display: none;" CssClass="btn btn-danger" Text="Delete" OnClick="btnDelete_Click1" />
</td>
</tr>
<tr>
<td colspan="3">
<div class="horizontalScroll" style="height: 100%; width: 100%; max-height: 100%">
<asp:GridView ID="gvPatientParent" runat="server" AutoGenerateColumns="false"
Font-Names="Verdana" AllowPaging="True" AllowSorting="True" PageSize="500"
OnPageIndexChanging="PageIndexChanging" BorderColor="#CCCCCC" BorderStyle="Solid"
Width="30%" BorderWidth="1px" OnSorting="Sorting" PagerSettings-Position="TopAndBottom" CssClass="table"
DataKeyNames="PatientId" OnRowDataBound="gvPatientParent_RowDataBound">
<AlternatingRowStyle BackColor="#BFE4FF" />
<PagerSettings Position="TopAndBottom" />
<PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<HeaderStyle Height="25px" BackColor="#6DC2FF" Font-Size="12px" BorderColor="#CCCCCC"
BorderStyle="Solid" BorderWidth="1px" />
<RowStyle Height="20px" Font-Size="11px" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<img alt="" id="imdHeaderExpCollapse" style="cursor: pointer" src="/images/Expand.png" />
</HeaderTemplate>
<ItemTemplate>
<img alt="" style="cursor: pointer" src="/images/plus.png" />
<asp:Panel ID="pnlOrders" runat="server" Style="display: none">
<asp:GridView ID="gvList" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" Font-Names="Verdana" AllowPaging="True" AllowSorting="True" PageSize="25"
CssClass="table" Width="100%" OnPageIndexChanging="PageIndexChanging" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px" OnSorting="Sorting" PagerSettings-Position="TopAndBottom">
<AlternatingRowStyle BackColor="#BFE4FF" />
<PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<HeaderStyle Height="25px" BackColor="#6DC2FF" Font-Size="12px" BorderColor="#CCCCCC"
BorderStyle="Solid" BorderWidth="1px" />
<RowStyle Height="20px" Font-Size="11px" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="50">
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server"
AutoPostBack="false" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkBxSelect" runat="server" AutoPostBack="false" Style="align-self: center; align-content: center;" />
</ItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="Client" HeaderText="Client" SortExpression="Client" />--%>
<%--<asp:BoundField DataField="PatientName" HeaderText="Patient Name" SortExpression="PatientName" />--%>
<asp:BoundField DataField="DateOfService" ItemStyle-Width="70"
ItemStyle-HorizontalAlign="Center"
HeaderText="DOS"
DataFormatString="{0:MM/dd/yyyy}">
<HeaderStyle Width="70px" />
</asp:BoundField>
<asp:BoundField DataField="PatientResponsibility" ItemStyle-Width="80"
ItemStyle-HorizontalAlign="Center"
HeaderText="Pt.Responsibility"
DataFormatString="{0:n}">
<HeaderStyle Width="80px" />
</asp:BoundField>
<asp:BoundField DataField="Pat_PaymentAmount" ItemStyle-Width="60"
ItemStyle-HorizontalAlign="Center"
HeaderText="Pt.PayAmount"
DataFormatString="{0:n}">
<HeaderStyle Width="60px" />
</asp:BoundField>
<asp:BoundField DataField="Pat_PaymentId" ItemStyle-Width="60"
ItemStyle-HorizontalAlign="Center"
HeaderText="Pt.PayId">
<HeaderStyle Width="60px" />
</asp:BoundField>
<asp:TemplateField HeaderText="IsReviewed" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:CheckBox ID="chkIsReviwed" Checked='<%# Convert.ToBoolean(Eval("reviewed")) %>' onclick="MarckCheck(this.id);" runat="server" Style="align-self: center; align-content: center;"
AutoPostBack="false" />
<%--<asp:CheckBox ID="chkIsReviwed" Checked='<%# ToBoolean.Parse(Eval("reviewed")) %>' onclick="MarckCheck(this.id);" runat="server" Style="align-self: center; align-content: center;"
AutoPostBack="false" />--%>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UpdatedDate" ItemStyle-Width="80"
ItemStyle-HorizontalAlign="Center"
HeaderText="UpdatedDate"
DataFormatString="{0:MM/dd/yyyy}">
<HeaderStyle Width="80px" />
</asp:BoundField>
</Columns>
</asp:GridView>
</asp:Panel>
<asp:HiddenField ID="IsExpanded" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="300px" DataField="PatientName" ItemStyle-HorizontalAlign="Center" HeaderText="Patient Name">
<ItemStyle HorizontalAlign="Center" Width="300px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Total Amount" ItemStyle-Width="150" ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:Label runat="server" Width="150px" Text='<%# Eval("patientResponsibility","{0:n}") %>' Visible="true"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</asp:Content>