In web application, How can i display current month calender in gridview, i mean calender dates as a columns. can you please tell me how can i start the coding or is there any reference. Thank you.
Display calendar in gridview using c# Asp.net
Using client side code:
<div class="col-lg-12 col-md-12 col-sm-12" style="padding-right: 15px;">
<div class="row panel panel-default" style="margin-bottom: 5px; padding: 10px; border-radius: 4px; border: 1px solid #c5c5c5; background: #f5f5f5;">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="padding: 0px;">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 table-responsive" style="padding-bottom: 5px;">
<div class="col-md-1">
<label style="font-size: medium;">Month</label>
<asp:DropDownList ID="drpMonth" runat="server"
ClientIDMode="Static" CssClass="chart-type form-control" Style="font-size: 14px;">
<asp:ListItem Text="Jan" Value="1"></asp:ListItem>
<asp:ListItem Text="Feb" Value="2"></asp:ListItem>
<asp:ListItem Text="Mar" Value="3"></asp:ListItem>
<asp:ListItem Text="Apr" Value="4"></asp:ListItem>
<asp:ListItem Text="May" Value="5"></asp:ListItem>
<asp:ListItem Text="Jun" Value="6"></asp:ListItem>
<asp:ListItem Text="Jul" Value="7"></asp:ListItem>
<asp:ListItem Text="Aug" Value="8"></asp:ListItem>
<asp:ListItem Text="Sep" Value="9"></asp:ListItem>
<asp:ListItem Text="Oct" Value="10"></asp:ListItem>
<asp:ListItem Text="Nov" Value="11"></asp:ListItem>
<asp:ListItem Text="Dec" Value="12"></asp:ListItem>
</asp:DropDownList>
</div>
<div class="col-md-1">
<label style="font-size: medium;">Year</label>
<asp:DropDownList ID="drpYear" runat="server"
ClientIDMode="Static" CssClass="chart-type form-control" Style="font-size: 14px; padding: 6px 10px;">
</asp:DropDownList>
</div>
<div class="col-md-2 dv-appointment">
<label style="color: #f5f5f5;">retrieve button text</label>
<asp:Button runat="server" ID="btnRetrieve" OnClick="btnRetrieve_Click" CssClass="btn btn-success" Text="Retrieve" />
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" style="text-align: center;">
<label title="" style="font-size: 18px !important; font-weight: 300 !important; color: #f12f2f;">
<%--Click on date to schedule a new appointment--%>
**Select date on the calendar to create a new appointment
</label>
</div>
<asp:Calendar DayStyle-Height="68px" ID="clAppointment" OnDayRender="clAppointment_DayRender"
runat="server" BackColor="#f1fbf0" BorderColor="#999999" BorderWidth="1px" DayNameFormat="Short" NextPrevStyle-ForeColor="#FFFFFF" NextPrevStyle-CssClass="pd-left-right"
names="Verdana" size="20pt" ForeColor="#484848" Height="100%" ShowGridLines="True"
Width="100%" Font-Bold="True" Font-Size="Medium" FirstDayOfWeek="Sunday">
<SelectedDayStyle BackColor="#CCCCFF"></SelectedDayStyle>
<SelectorStyle BackColor="#FFCC66"></SelectorStyle>
<TodayDayStyle ForeColor="#FF6600" BackColor="#bce0cc"></TodayDayStyle>
<OtherMonthDayStyle ForeColor="#d2a87e82"></OtherMonthDayStyle>
<%--#CC9966--%>
<DayHeaderStyle BackColor="#bce4ab" CssClass="text-center" Height="3px" Font-Bold="True" Font-Size="Medium"></DayHeaderStyle>
<TitleStyle BackColor="#666666" Font-Size="Medium" ForeColor="White" Font-Bold="True" Height="8.8px"></TitleStyle>
</asp:Calendar>
</div>
</div>
Using server side Code:
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Commerce.Clinics
{
public partial class Appointment_Calendar : BaseClass
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int CurrentYear = DateTime.Now.Year;
drpMonth.SelectedValue = DateTime.Now.Month.ToString();
drpYear.Items.Add(new ListItem(Convert.ToString(CurrentYear - 1), Convert.ToString(CurrentYear - 1)));
drpYear.Items.Add(new ListItem(Convert.ToString(CurrentYear), Convert.ToString(CurrentYear)));
drpYear.Items.Add(new ListItem(Convert.ToString(CurrentYear + 1), Convert.ToString(CurrentYear + 1)));
drpYear.SelectedValue = Convert.ToString(CurrentYear);
string strMinDate = Convert.ToInt32(drpMonth.SelectedValue) + "/" + "01/" + Convert.ToString(CurrentYear);
string strMaxDate = Convert.ToInt32(drpMonth.SelectedValue) + "/" + DateTime.DaysInMonth(CurrentYear, Convert.ToInt32(drpMonth.SelectedValue)) + "/" + Convert.ToString(CurrentYear);
Session["ScheduleDate"] = GetBookedAppointmentByClinic(strMinDate, strMaxDate);
}
}
protected void clAppointment_DayRender(object sender, DayRenderEventArgs x)
{
int ApptBooked = 0;
string booked = "", booked1 = "";
TableCell cell = (TableCell)x.Cell;
if (Convert.ToInt32(SessionFactory.CurrentUser.LocationId) != 0)
{
x.Day.IsSelectable = false;
CalendarDay day = (CalendarDay)x.Day;
DataTable dtbooked = (DataTable)Session["ScheduleDate"];
DataRow[] drSelect = dtbooked.Select("apptdate='" + day.Date.ToString("MM/dd/yyyy") + "'");
if (drSelect.Length > 0)
{
ApptBooked = Convert.ToInt32(drSelect[0]["apptcount"]);
}
if (ApptBooked > 0)
{
booked = "<font color='#b53737'>";
booked1 = "</font>";
}
if (day.IsOtherMonth)
{
x.Cell.Text = "";
x.Cell.BackColor = System.Drawing.Color.White;
}
//else if (day.Date.ToString("dddd") == "Saturday" || day.Date.ToString("dddd") == "Sunday")
//{
// cell.BackColor = System.Drawing.Color.White;
//}
// Bind Booked appotionment for spacific location and department.
//else if (ucLocationDept.LocationId != "0" && ucLocationDept.DepartmentId != "0")
//{
else if (day.Date < DateTime.Today.Date && ApptBooked == 0)
{
}
else
{
cell.Controls.Add(new LiteralControl("<br/><a class='schedlnk' style='font-size:medium;color:green;cursor:pointer;' href=EmployeeAppointment.aspx?date=" + day.Date.ToString("MM/dd/yyyy") + ">" + booked + +ApptBooked + " Booked " + booked1 + "</a>"));
}
/*}
else
{
cell.Controls.Add(new LiteralControl("<br/><a class='schedlnk' style='font-size:medium;color:green;cursor:pointer;'>" + booked + ApptBooked + " Booked" + booked1 + "</a>"));
}*/
}
}
public DataTable GetBookedAppointmentByClinic(string StartDate, string EndDate)
{
SqlParameter[] PM = new SqlParameter[]
{
new SqlParameter("#Mode", "Mode_Name"),
new SqlParameter("#StartDate", StartDate),
new SqlParameter("#EndDate", EndDate),
new SqlParameter("#LocationId", Convert.ToInt32(SessionFactory.CurrentUser.LocationId)),
};
DataTable dt = SqlHelper.ExecuteDataset(new SqlConnection(SqlHelper.GetConnectionString()), CommandType.StoredProcedure, "ProcName", PM).Tables[0];
return dt;
}
#endregion
protected void btnRetrieve_Click(object sender, EventArgs e)
{
clAppointment.SelectedDates.Clear();
clAppointment.VisibleDate = new DateTime(Convert.ToInt32(drpYear.SelectedValue), Convert.ToInt32(drpMonth.SelectedValue), 1);
string strMinDate = Convert.ToString(drpYear.SelectedValue) + "-" + Convert.ToString(drpMonth.SelectedValue) + "-01";
string strMaxDate = Convert.ToString(drpYear.SelectedValue) + "-" + Convert.ToString(drpMonth.SelectedValue) + "-" + DateTime.DaysInMonth(Convert.ToInt32(drpYear.SelectedValue), Convert.ToInt32(drpMonth.SelectedValue));
Session["ScheduleDate"] = GetBookedAppointmentByClinic(strMinDate, strMaxDate);
}
}
}
add a TemplateField to your GridView and insert a calendar to the TemplateField, like this:
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Calendar ID="Calendar2" runat="server"></asp:Calendar>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Related
I have a problem when I edit data select from grid view and update on bootstrap modal.
ASPX:
<asp:GridView ID="gvcat" CssClass="table table-bordered font-13" Width="500px" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lnkView" runat="server" CommandArgument='<%# Eval("ID") %>' OnClick="lnkView_Click" data-toggle="modal" data-target="#myModal" causesvalidation="false">View</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
String CS = ConfigurationManager.ConnectionStrings["TFRWebAppConnectionString"].ConnectionString;
using (SqlConnection sqlCon = new SqlConnection(CS))
{
if (sqlCon.State == ConnectionState.Closed)
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("CategoryCreateOrUpdate", sqlCon);
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#ID", (hfID.Value == "" ? 0 : Convert.ToInt32(hfID.Value)));
sqlCmd.Parameters.AddWithValue("#Name", txtName.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Description", txtDescription.Text.Trim());
sqlCmd.ExecuteNonQuery();
gvcat.DataBind();
}
}
catch (Exception)
{
}
protected void lnkView_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["TFRWebAppConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
int ID = Convert.ToInt32((sender as LinkButton).CommandArgument);
using (SqlCommand cmd = new SqlCommand("SELECT * from tblCategory WHERE ID = #ID", con))
{
cmd.Parameters.AddWithValue("#ID", ID); // this line was mising in your code
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dtcategory = new DataTable();
sda.Fill(dtcategory);
con.Close();
hfID.Value = ID.ToString();
txtName.Text = dtcategory.Rows[0]["Name"].ToString();
txtDescription.Text = dtcategory.Rows[0]["Description"].ToString();
}
}
}
}
aspx body:
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×</button>
<h4 class="modal-title">
Add New Metal Group</h4>
</div>
<div class="modal-body">
<asp:HiddenField ID="hfID" runat="server" />
<div class="row">
<div class="form-group-sm">
<div class="col-md-3">
<asp:TextBox ID="txtName" CssClass="form-control" placeholder="Category Name" type="text" runat="server"></asp:TextBox>
<asp:TextBox ID="txtDescription" CssClass="form-control" placeholder="Description" type="text" runat="server"></asp:TextBox>
<%-- <asp:RequiredFieldValidator ID="RequiredFieldValidatorDescription" CssClass="text-danger" runat="server" ErrorMessage="This field is Required !" ControlToValidate="txtDescription"></asp:RequiredFieldValidator>--%>
</div>
</div>
</div>
<div class="row">
<div class="form-group-sm">
<div class="col-md-6">
<asp:Button ID="btnSave" CssClass="btn btn-sm" runat="server" OnClick="btnSave_Click" Text="Save" />
<asp:Button ID="btnClear" CssClass="btn btn-sm" runat="server" OnClick="btnClear_Click" Text="Clear" />
</div>
</div>
</div>
</div>
</div>
</div>
This is driving me crackers, it's very basic code, just a very basic three textbox contact form and a linkbutton.
<div class="form-group has-feedback">
<asp:Label ID="lblYourName" AssociatedControlID="txtYourName" CssClass="col-sm-3 control-label" runat="server" Text="Your name"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtYourName" TextMode="SingleLine" CssClass="form-control" runat="server" placeholder="Your name"></asp:TextBox>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
<asp:Label ID="lblNoName" runat="server" Visible="false" Text="Please enter your name"></asp:Label>
</div>
</div>
<div class="form-group has-feedback">
<asp:Label ID="lblEmail" runat="server" AssociatedControlID="txtEmail" Text="Email" CssClass="col-sm-3 control-label"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtEmail" CssClass="form-control" runat="server" placeholder="Email" TextMode="Email"></asp:TextBox>
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
<asp:Label ID="lblNoEmail" runat="server" Visible="false" Text="Please enter your email"></asp:Label>
</div>
</div>
<div class="form-group">
<asp:Label ID="lblMessage" AssociatedControlID="txtMessage" CssClass="col-sm-3 control-label" runat="server" Text="Your message"></asp:Label>
<div class="col-sm-6">
<asp:TextBox ID="txtMessage" CssClass="form-control" TextMode="MultiLine" placeholder="Your message" runat="server"></asp:TextBox>
</div>
</div>
<div class="row">
<div class="col-sm-offset-3 col-sm-6">
<asp:LinkButton ID="lnkSubmit" runat="server" OnClick="lnkSubmit_Click" CssClass="btn standard-hover-effect bg-red btn-lg btn-block">
<span class="text">Contact us <i class="fa fa-arrow-right"></i></span>
</asp:LinkButton>
</div>
</div>
The OnClick of the linkbutton points to this simple MailMessage method where it checks name and email boxes are filled in and then sends an email.
protected void lnkSubmit_Click(object sender, EventArgs e)
{
lblNoName.Visible = false;
lblNoEmail.Visible = false;
if (string.IsNullOrEmpty(txtYourName.Text) || string.IsNullOrEmpty(txtEmail.Text))
{
if (!string.IsNullOrEmpty(txtYourName.Text))
{
lblNoName.Visible = false;
}
else
{
lblNoName.Visible = true;
}
if (!string.IsNullOrEmpty(txtEmail.Text))
{
lblNoEmail.Visible = false;
}
else
{
lblNoEmail.Visible = true;
}
}
else
{
MailMessage mm = new MailMessage(txtEmail.Text, "foo#bar.com");
mm.Subject = "Feedback from website";
mm.Body = "Email from " + txtYourName.Text + "<br /><br />" + txtMessage.Text;
SmtpClient smtp = new SmtpClient();
smtp.Host = "mail.websitelive.net";
smtp.Send(mm);
panContactThanks.Visible = true;
}
}
But when I click the submit button, nothing happens. At all. The OnClick doesn't even fire so the breakpoint in the code behind doesn't even get called. It's as if the OnClick even isn't even in the code and it's just a dummy button. What have I missed out?
Please try CauseValidation="false" in link button.
Like:
<asp:LinkButton ID="lnkSubmit" runat="server" OnClick="lnkSubmit_Click"
CauseValidation="false" CssClass="btn standard-hover-effect bg-red btn-lg btn-block">
Wrap your html inside form tag
<form id="someForm" runat="server">
<!--your html-->
</form>
You are using .net server controls, so you need to wrap them inside form. Don't forget to add runat="server"
http://forums.asp.net/t/1463877.aspx?Does+an+aspx+must+have+a+form+tag+
Probably you forgot to add the isPostBack condition in your Page_load
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Control initialization here
}
}
Take a look at ASP.NET page life cycle: https://msdn.microsoft.com/en-us/library/ms178472.aspx
IsPostBack: https://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback(v=vs.110).aspx
Im write code for Drop down list selected value add the the list box and text filed , i can remove the list box value but cant remove the text filed value, please how to write code remove the same adding value for text filed and list box
Im add the dropdownlist value AA, Its display list box and text box, but click the remove button always removed selected List Box item but not remove text box value
<div class="col-sm-3">
<asp:TextBox ID="txtQlt" runat="server" CssClass="form-control" Width="348px" OnTextChanged="txtQlt_TextChanged" ReadOnly="true"></asp:TextBox>
</div><div class="col-md-1" style="margin-left:115px;">
<asp:Label ID="Label4" runat="server" ForeColor="Red" Text="*" ></asp:Label>
</div>
</div>
<br />
<div class="row">
<div class="col-sm-2">
<asp:Label ID="Label6" runat="server" Text="Quality reference" Font-Bold="True" Font-Names="arial, helvetica, sans-serif" Font-Size="13px"></asp:Label>
</div>
<div class="col-sm-3">
<asp:DropDownList ID ="cmbQualityRef" runat ="server" CssClass="form-control" Width="250px" >
</asp:DropDownList>
<asp:ListBox ID="lstValue" runat="server" CssClass="content" Rows="5" ValidationGroup="save"
Width="250" ></asp:ListBox>
</div>
<asp:ImageButton ID="btnAdd" runat="server" CssClass="button" Text="Add" ValidationGroup="add"
OnClick="btnAdd_Click" ImageUrl="~/img/Add.png"/>
<asp:ImageButton ID="btnImageRemove" runat="server" OnClick="btnImageRemove_Click"
ImageUrl="~/img/Remove.png" />
<div class="col-md-1" style="margin-left:16px;">
<asp:Label ID="Label7" runat="server" ForeColor="Red" Text="*" ></asp:Label>
</div>
</div>
protected void btnAdd_Click(object sender, EventArgs e)
{
AddToList();
lstValue.Items.Remove("");
}
--------------------------------------------
private void AddToList()
{
if (lstValue.Items.FindByText(cmbQualityRef.SelectedItem.ToString()) == null)
{
if (lstValue.Items.Count > 0)
{
txtQlt.Text = txtQlt.Text + "," + cmbQualityRef.SelectedItem.ToString();
}
else
{
txtQlt.Text = cmbQualityRef.SelectedItem.ToString();
}
ListItem itm = new ListItem();
itm.Value = cmbQualityRef.SelectedValue;
itm.Text = cmbQualityRef.SelectedItem.ToString();
lblMsg.Text = "";
lstValue.Items.Add(itm);
}
else
{
lblMsg.Text = "Selected Item Already Exists In The List.";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
protected void btnImageRemove_Click(object sender, ImageClickEventArgs e)
{
try
{
if (lstValue.SelectedItem != null)
{
lstValue.Items.Remove(lstValue.SelectedItem);
txtQlt.Text = txtQlt.Text.Replace(lstValue.SelectedItem.ToString(), "").Trim();
}
}
catch (Exception)
{
}
}
You should remove item from list after replacing the string,other wise it can't find the item from list.
Your code looks like:
protected void btnRemove_Click(object sender, EventArgs e)
{
try
{
if (lst.SelectedItem != null)
{
txt.Text = txt.Text.Replace(lst.SelectedItem.ToString(), "").Trim();
lst.Items.Remove(lst.SelectedItem);
}
}
catch (Exception)
{
}
}
asp DropDownList inside ListView with UpdatePanel. SelectedIndexChanged Not fire when select item from dropdownlist.
Already Tryied Every Solution.
OnPageLoad()
!isPost
AutoPostBack="True"
ViewStateMode="Enabled"
EnableViewState="true"
<asp:ListView ID="productListView" runat="server" OnItemDataBound="productListView_ItemDataBound">
<ItemTemplate>
<div class="item col-lg-3 col-md-4 col-sm-6 col-xs-12">
<div class="hovereffect">
<div class="overlay">
<div class="selection">
<asp:Label runat="server" CssClass="lblShowTag">BRAND:</asp:Label>
<asp:DropDownList ID="ddlBrand" runat="server" CssClass="branddrop" AutoPostBack="True" OnSelectedIndexChanged="ddlBrand_SelectedIndexChanged" ViewStateMode="Enabled" EnableViewState="true">
</asp:DropDownList>
<asp:UpdatePanel ID="updatePanel" runat="server" >
<ContentTemplate>
<asp:Label runat="server" ID="lblShowTag" text="PRICE: " CssClass="lblShowTag"/><asp:Label runat="server" ID="lblEachPrice" CssClass="lblEachPrice"/>
<div class="clearfix"></div>
<asp:Label runat="server" class="lblShowTag">QUANTITY: </asp:Label>
<asp:TextBox ID="txtQuantity" runat="server" Text="1" CssClass='txtquantity' />
<div class="clearfix"></div>
<asp:Label runat="server" ID="Label1" text="TOTAL: " CssClass="lblShowTag"/><asp:Label runat="server" ID="lblTotalPrice" CssClass="lblEachPrice" ForeColor="Green" Text="5000"/>
<div class="clearfix"></div>
<asp:Label id="lblError" runat="server" Text="Label 2" ForeColor="Red"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlBrand" EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
</div>
</div>
</div>
</div>
</ItemTemplate>
<EmptyDataTemplate>
<h3>Sorry...No Product Availabel</h3>
</EmptyDataTemplate>
</asp:ListView>
C# Code:
protected void Page_Load(object sender, EventArgs e)
{
//showProdutListView();
String CateId = Request.QueryString["CateId"];
if (!String.IsNullOrEmpty(CateId))
{
showProdutListView(CateId);
}
else
{
Response.Redirect("/default.aspx");
}
if (!IsPostBack)
{
if (Session["myCart"] != null)
{
DataTable dt = (DataTable)Session["myCart"];
cartQuantity = dt.Rows.Count.ToString();
}
else
{
cartQuantity = "0";
}
((ProdutcPageNested)Master).OnProductMasterPage.Text = "Cart Items: " + cartQuantity;
ShowBrand();
}
}public void ddlBrand_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (ListViewItem item in productListView.Items)
{
DropDownList ddl = (DropDownList)sender;
lblEachPrice.Text = ddl.SelectedValue.ToString();
}
}
The problem here is you are binding data on page load, so whenever DDL is posting page loads new values causing not to fire OnSelectdIndedChanged event. Here is my solution hope it works.
this should be replaced
if (!String.IsNullOrEmpty(CateId))
{
showProdutListView(CateId);
}
else
{
Response.Redirect("/default.aspx");
}
if (!IsPostBack)
{
if (Session["myCart"] != null)
{
DataTable dt = (DataTable)Session["myCart"];
cartQuantity = dt.Rows.Count.ToString();
}
else
{
cartQuantity = "0";
}
((ProdutcPageNested)Master).OnProductMasterPage.Text = "Cart Items: " + cartQuantity;
ShowBrand();
}
with this
if (!IsPostBack)
{
if (!String.IsNullOrEmpty(CateId))
{
showProdutListView(CateId);
}
else
{
Response.Redirect("/default.aspx");
}
if (Session["myCart"] != null)
{
DataTable dt = (DataTable)Session["myCart"];
cartQuantity = dt.Rows.Count.ToString();
}
else
{
cartQuantity = "0";
}
((ProdutcPageNested)Master).OnProductMasterPage.Text = "Cart Items: " + cartQuantity;
ShowBrand();
}
I am using Nested GridView. How can I use only div tags and any other controls to achieve the Nested GridView functionality ?
Javascript is
<script language="javascript" type="text/javascript">
function divexpandcollapse(divname) {
var div = document.getElementById(divname);
var img = document.getElementById('img' + divname);
if (div.style.display == "none") {
div.style.display = "inline";
img.src = "minus.gif";
} else {
div.style.display = "none";
img.src = "plus.gif";
}
}
</script>
And the aspx contain two a gridview( with nested gridviews) as
<div>
<asp:GridView ID="gvParentGrid" runat="server" DataKeyNames="CountryId" Width="300"
AutoGenerateColumns="false" OnRowDataBound="gvUserInfo_RowDataBound" GridLines="None" BorderStyle="Solid" BorderWidth="1px" BorderColor="#df5015">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField ItemStyle-Width="20px">
<ItemTemplate>
<a href="JavaScript:divexpandcollapse('div<%# Eval("CountryID") %>');">
<img id="imgdiv<%# Eval("CountryID") %>" width="9px" border="0" src="plus.gif" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="CountryId" HeaderText="CountryId" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="CountryName" HeaderText="CountryName" HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="div<%# Eval("CountryID") %>" style="display: none; position: relative; left: 15px; overflow: auto">
<asp:GridView ID="gvChildGrid" runat="server" AutoGenerateColumns="false" BorderStyle="Double" BorderColor="#df5015" GridLines="None" Width="250px">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="StateID" HeaderText="StateID" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="StateName" HeaderText="StateName" HeaderStyle-HorizontalAlign="Left" />
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
And Code behind is
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
// This method is used to bind gridview from database
protected void BindGridview()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Country", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gvParentGrid.DataSource = ds;
gvParentGrid.DataBind();
}
protected void gvUserInfo_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
con.Open();
GridView gv = (GridView)e.Row.FindControl("gvChildGrid");
int CountryId = Convert.ToInt32(e.Row.Cells[1].Text);
SqlCommand cmd = new SqlCommand("select * from State where CountryID=" + CountryId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gv.DataSource = ds;
gv.DataBind();
}
EDIT :
You can use Nested Repeaters. In outer repeater you have to add two repeaters, one for ItemTemplate and another for AlternatingItemTemplate. Your markup may look like this:
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function divexpandcollapse(divname) {
var div = document.getElementById(divname);
var img = document.getElementById('img' + divname);
if (div.style.display == "none") {
div.style.display = "inline";
img.src = "minus.gif";
} else {
div.style.display = "none";
img.src = "plus.gif";
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<asp:Repeater ID="rptCountry" runat="server" OnItemDataBound="rptCountry_ItemDataBound">
<HeaderTemplate>
<table style="border: 1px double #df5015" width="300">
<tr>
<th style="background-color: #df5015; font-weight: bold; color: white"></th>
<th style="background-color: #df5015; font-weight: bold; color: white">CountryId</th>
<th style="background-color: #df5015; font-weight: bold; color: white">CountryName</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color: #E1E1E1">
<td style="width: 20px">
<a href="JavaScript:divexpandcollapse('div<%# Eval("CountryID") %>');">
<img id='imgdiv<%# Eval("CountryID") %>' width="9px" border="0" src="plus.gif" />
</a>
</td>
<td><%#Eval("CountryID") %></td>
<td><%#Eval("CountryName") %></td>
</tr>
<tr style="background-color: #E1E1E1">
<td colspan="3">
<asp:HiddenField ID="hdnCountryID" runat="server" Value='<%#Eval("CountryID") %>' />
<div id='div<%# Eval("CountryID") %>' style="display: none; position: relative; left: 15px; overflow: auto">
<asp:Repeater ID="rptState" runat="server">
<HeaderTemplate>
<table style="border: 1px double #df5015" width="250">
<tr>
<th style="background-color: black; font-weight: bold; color: white">StateID</th>
<th style="background-color: black; font-weight: bold; color: white">StateName</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color: #E1E1E1">
<td><%#Eval("StateID") %></td>
<td><%#Eval("StateName") %></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color: White">
<td><%#Eval("StateID") %></td>
<td><%#Eval("StateName") %></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color: white">
<td style="width: 20px">
<a href="JavaScript:divexpandcollapse('div<%# Eval("CountryID") %>');">
<img id='imgdiv<%# Eval("CountryID") %>' width="9px" border="0" src="plus.gif" />
</a>
</td>
<td><%#Eval("CountryID") %></td>
<td><%#Eval("CountryName") %></td>
</tr>
<tr style="background-color: white">
<td colspan="3">
<asp:HiddenField ID="hdnCountryID" runat="server" Value='<%#Eval("CountryID") %>' />
<div id='div<%# Eval("CountryID") %>' style="display: none; position: relative; left: 15px; overflow: auto">
<asp:Repeater ID="rptState" runat="server">
<HeaderTemplate>
<table style="border: 1px double #df5015" width="250">
<tr>
<th style="background-color: black; font-weight: bold; color: white">StateID</th>
<th style="background-color: black; font-weight: bold; color: white">StateName</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color: #E1E1E1">
<td><%#Eval("StateID") %></td>
<td><%#Eval("StateName") %></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr style="background-color: White">
<td><%#Eval("StateID") %></td>
<td><%#Eval("StateName") %></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate></table></FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
And the code:
//Change the connection string with yours
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SOConnectionString1"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeater();
}
}
// This method is used to bind gridview from database
protected void BindRepeater()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Country", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
rptCountry.DataSource = ds;
rptCountry.DataBind();
}
protected void rptCountry_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var rptState = e.Item.FindControl("rptState") as Repeater ;
var hdnCountryID = e.Item.FindControl("hdnCountryID") as HiddenField ;
int countryId = 0;
DataSet ds = new DataSet();
if (rptState != null && hdnCountryID != null && int.TryParse(hdnCountryID.Value, out countryId))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from State where CountryID=" + countryId, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
rptState.DataSource = ds;
rptState.DataBind();
}
}
And here's the result: