Delete Individual row of gridview without deleting from database - c#

I am using Linq-to-SQL in ASP.NET & C#. I want to delete individual row of gridview by click on delete button (i.e. CommandField or TemplateField) with gridTrainingNeed_RowDeleting event.
Here is my code for loading gridview on page load.
int departmentId;
int branchId;
int positionId;
double month;
int levelId;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Initialize();
}
}
public void Initialize()
{
ddlBranch.DataSource = TrainingManager.GetBranchName();
ddlBranch.DataBind();
ddlDepartment.DataSource = DepartmentManager.GetAllDepartments();
ddlDepartment.DataBind();
ddlPosition.DataSource = TrainingManager.GetDesignationName();
ddlPosition.DataBind();
ddlLevel.DataSource = TrainingManager.GetLevelName();
ddlLevel.DataBind();
gridTrainingNeed.DataSource = TrainingManager.GetAllEmployees(departmentId, branchId, positionId, month, levelId).ToList();
gridTrainingNeed.DataBind();
}
Now I am going to keep my design code:
<div class="innerLR">
<div class="seperator bottom" />
<div class="widget">
<div class="widget-head">
<h4 class="heading">
Send Circulation To
</h4>
</div>
<div class="widget-body">
<table class="tableShow" cellpadding="3" cellspacing="0">
<tr>
<td>
<asp:DropDownList ID="ddlBranch" runat="server" DataTextField="Name"
DataValueField="BranchId" Width="170px" AppendDataBoundItems="True"
>
<asp:ListItem Text="---Select Branch---"/>
</asp:DropDownList>
</td>
<td>
<asp:DropDownList ID="ddlDepartment" runat="server" AppendDataBoundItems="True"
DataTextField="Name" Width="170px" DataValueField="DepartmentId">
<asp:ListItem Text="---Select Department---"/>
</asp:DropDownList></td>
<td>
<asp:DropDownList ID="ddlLevel" runat="server" DataTextField="Name"
DataValueField="LevelId" Width="170px" AppendDataBoundItems="True"
>
<asp:ListItem Text="---Select Level---"/>
</asp:DropDownList></td>
<td>
<asp:DropDownList ID="ddlPosition" runat="server" DataTextField="Name"
DataValueField="DesignationId" Width="170px" AppendDataBoundItems="True"
>
<asp:ListItem Text="---Select Position---"/>
</asp:DropDownList></td>
</tr>
<tr>
<td>
<br />
Send Circulation To</td>
<td>
<br />
Month</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlCirculation" runat="server" DataTextField="Name"
DataValueField="PositionId" Width="170px" AutoPostBack="true" AppendDataBoundItems="True"
onselectedindexchanged="ddlCirculation_SelectedIndexChanged">
<asp:ListItem Text="" Value="-1" />
<asp:ListItem Text="All" Value="0" />
<asp:ListItem Text="Must Have Worked For" Value="1" />
</asp:DropDownList></td>
<td>
<asp:TextBox ID="txtMonth" Width="150px" runat="server" Enabled="false"></asp:TextBox></td>
<td>
<asp:Button ID="btnShow" runat="server" Text="Show" onclick="btnShow_Click" /></td>
<td>
</td>
</tr>
</table>
</div>
</div>
<div>
<asp:GridView ID="gridTrainingNeed" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" CellPadding="4" ForeColor="#333333"
GridLines="None" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="EmployeeId" HeaderText="EID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Branch" HeaderText="Branch" />
<asp:BoundField DataField="Department" HeaderText="Department" />
<asp:BoundField DataField="Level" HeaderText="Level" />
<asp:BoundField DataField="Position" HeaderText="Position" />
<asp:CommandField HeaderText="Delete" ShowCancelButton="False"
ShowDeleteButton="True" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
</div>
</div>
Thus, I want to delete row one by one with RowDeleting Event from displaying data on gridview not from database.
protected void gridTrainingNeed_RowDeleting(object sender, GridViewDeleteEventArgs e)
{//Row delete code
}
Thank You.

Instead of assigning the DataSource directly like you are doing:
gridTrainingNeed.DataSource = TrainingManager.GetAllEmployees(departmentId, branchId, positionId, month, levelId).ToList();
Store the result in Page level List. Define a page level List like:
//Define List at page/class level
List<Employee> gridList = new List<Employee>();
Then in your method Initialize
gridList = TrainingManager.GetAllEmployees(departmentId, branchId, positionId, month, levelId).ToList();
gridTrainingNeed.DataSource = gridList;
gridTrainingNeed.DataBind();
You need to persist the List<Employee> in memory on PostBack, Use Session/ViewState etc. (See ASP.Net State Management).
Later in your gridTrainingNeed_RowDeleting, get the ID from row or any field that uniquely identify an employee. Query your list and remove that object from the List in memory. Re-assign the DataSource to the modified list and call DataBind.

Related

how to get values from gridview in asp.net web forms?

hello all i am new to asp.net and i want to get values from grid view when i click on Edit or Delete or and i don't know how to do it i am sending data table to show table data and i don't want to use SQL Data Source from Visual tool box.
i have tried the following code but it gives error
protected void dgv1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
int rowindex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
dgv1.EditIndex = rowindex;
dgv1.DataBind();
}
}
}
my view page code is as follows
<form id="form1" class="form-control form-group" runat="server">
<asp:Panel ID="pnlAddCustomers" runat="server" Height="376px">
<asp:Label ID="lblAddCustomers" runat="server" Text="Add Customers"></asp:Label>
<br runat="server"/>
<asp:Label ID="labelAddName" Text="Customer Name" runat="server"></asp:Label>
<asp:TextBox ID="txtboxcustomername" runat="server" Height="16px"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text=" Customer City "></asp:Label>
<asp:TextBox ID="txtboxcity" runat="server"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text=" Customer Telephone "></asp:Label>
<asp:TextBox ID="txtboxtelephone" runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server" Text="Add Customers" Height="57px" Width="208px" OnClick="Button1_Click" />
</asp:Panel>
<asp:Panel ID="PnlViewCustomers" CssClass="table-dark" runat="server" Height="408px" >
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
<asp:GridView ID="dgv1" runat="server" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" EnableTheming="True" PageSize="5" Width="100%" OnRowCommand="dgv1_RowCommand">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
</asp:Panel>
</form>
and body pic is as follow
enter image description here
Try this:
LinkButton lnkBtn = (LinkButton)e.CommandSource; // the button
GridViewRow gvRow = (GridViewRow)lnkBtn.Parent.Parent; // the row
You may also get the data key index by adding DataKeyNames="MyTableKeyID" to the <asp:GridView /> tab, then
string selectedKeyIndex = this.GridView1.DataKeys[myRow.RowIndex]["MyTableKeyID"].ToString();

Not able to display selected value in drop down list in asp.net

I have a dropdownlist , i can see list item from 1 to 10, however when I select any one of the value it doesnt display in dropdownlist,
<asp:DropDownList ID="ddlqty" runat="server" CssClass="myselect">
<asp:ListItem Value="1" Selected="True">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="5">5</asp:ListItem>
<asp:ListItem Value="6">6</asp:ListItem>
<asp:ListItem Value="7">7</asp:ListItem>
<asp:ListItem Value="8">8</asp:ListItem>
<asp:ListItem Value="9">9</asp:ListItem>
<asp:ListItem Value="10">10</asp:ListItem>
</asp:DropDownList>
what am i missing here. Also when in code behind intellisense not getting ddlqty which is the ID of the dropdownlist.
This is the HTML I am getting from the browser:
<select name="Repeater1$ctl01$ddlqty" id="Repeater1_ddlqty_0" class="myselect">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
My Repeater class
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr class="cart_item">
<td class="product-thumbnail">
<a href="#">
<img src=" images/ecommerce/products/hoodie_1_front-150x150.jpg" alt=""></a>
</td>
<td class="product-name"><%#Eval("ItemName") %>
<dl class="variation">
<dt class="variation-Color">Category:</dt>
<dd class="variation-Color">
<p><%#Eval("Category") %></p>
</dd>
</dl>
</td>
<td class="product-price"><span class="amount"><%#Eval("Rate") %></span></td>
<td class="product-quantity">
<%-- -
<input type="text" value="1"> +</td>--%>
<%--<input type="text" value="1" readonly="true">--%>
<asp:DropDownList ID="ddlqty" runat="server" CssClass="myselect">
<asp:ListItem Value="1" Selected="True">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
<asp:ListItem Value="4">4</asp:ListItem>
<asp:ListItem Value="5">5</asp:ListItem>
<asp:ListItem Value="6">6</asp:ListItem>
<asp:ListItem Value="7">7</asp:ListItem>
<asp:ListItem Value="8">8</asp:ListItem>
<asp:ListItem Value="9">9</asp:ListItem>
<asp:ListItem Value="10">10</asp:ListItem>
</asp:DropDownList>
<%--<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="Edit" Text="Change" Font-Size="Small"></asp:LinkButton>--%>
<td class="product-subtotal"><span class="amount">$ <%#Eval("Rate") %></span></td>
<td class="product-remove"><i class="fa fa-times"></i></td>
</tr>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
Please help
Try to get the DropDownList value using foreach loop
foreach(RepeaterItem item in rpt1.Items)
{
DropDownList ddl = (DropDownList)item.FindControl("ddl");
string ddl_value = ddl.SelectedValue;
}
Note: rpt1 is Repeater's Id
also note that by using foreach loop you'll get all dropdownlist's
value, so you have to use it according your scenario.
When a Control is inside a Repeater, you cannot access it directly. You will have to use FindControl with an Index number of the Item that contains the Control inside the Repeater.
DropDownList drp = Repeater1.Items[index].FindControl("ddlqty") as DropDownList;
drp.SelectedValue = "2";
UPDATE
If you want to set the DropDownList values from the cart, and update the cart when you change the items you can do this by adding OnItemDataBound and OnSelectedIndexChanged
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<asp:DropDownList ID="ddlqty" runat="server" OnSelectedIndexChanged="ddlqty_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Value="1">1</asp:ListItem>
<asp:ListItem Value="2">2</asp:ListItem>
<asp:ListItem Value="3">3</asp:ListItem>
</asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("tocht_id") %>' Visible="false"></asp:Label>
</ItemTemplate>
</asp:Repeater>
Code behind
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
int itemsInCart = 3;
//find the dropdownlist using findcontrol
DropDownList drp = e.Item.FindControl("ddlqty") as DropDownList;
//set the correct cart value
drp.SelectedValue = itemsInCart.ToString();
}
protected void ddlqty_SelectedIndexChanged(object sender, EventArgs e)
{
//cast the sender back to a dropdownlist
DropDownList drp = sender as DropDownList;
//get the item as a repeater item
RepeaterItem item = drp.NamingContainer as RepeaterItem;
//find the label with the product ID in the Repeater
Label lbl = Repeater1.Items[item.ItemIndex].FindControl("Label1") as Label;
//get the product id from the attri
int productID = Convert.ToInt32(lbl.Text);
//convert the selectedvalue back to an int
int itemsInCart = Convert.ToInt32(drp.SelectedValue);
//you now have the product id and the new cart amount
}
Below is the code that will use to Bind Repeater at page load under IsPostback condition on page load event
private void BindData()
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", Type.GetType("System.String"));
dt.Columns.Add("ItemName", Type.GetType("System.String"));
dt.Columns.Add("Category", Type.GetType("System.String"));
dt.Columns.Add("Rate", Type.GetType("System.String"));
dt.Columns.Add("Qty", Type.GetType("System.String"));
dt.Columns.Add("Total", Type.GetType("System.String"));
for (int i = 1; i <= 10; i++)
{
DataRow dr = dt.NewRow();
dr["ID"] = 1;
dr["ItemName"] = "hoodie";
dr["Category"] = "Hoodie";
dr["Rate"] = 25;
dr["Qty"] = 4;
dr["Total"] = (4 * 25);
dt.Rows.Add(dr);
}
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList ddlQty = new DropDownList();
ddlQty = (DropDownList)e.Item.FindControl("ddlqty");
HiddenField hdn = new HiddenField();
hdn = (HiddenField)e.Item.FindControl("hdnQty");
if (hdn.Value != "")
{
ddlQty.SelectedItem.Selected = false;
ddlQty.Items.FindByValue(hdn.Value).Selected = true;
}
}
}
You need to use ItemDataBound event of Repeater that will give you control at the time of binding data to repeater and you can change value of that control while binding records.
Another thing that you have to do is to handle dropdown selected index event that will give you value of qty and you can use it to rebind repeater.
I am able to solve my issue, now i can see selected value in the text of dropdownlist. However i have to remove Repeater. And used gridview instead. I am having 1 issue that when I click on Save using <asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" Text="Save" ></asp:LinkButton> it refreshes the page and value again goes to 1 which is by default value.
Heres my code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="slno" ForeColor="#333333" GridLines="None" HorizontalAlign="Center" Width="100%" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowUpdating="GridView1_RowUpdating">
<RowStyle HorizontalAlign="Center" VerticalAlign="Middle" BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:BoundField DataField="slno" HeaderText="Sl No" ReadOnly="true">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="itemname" HeaderText="Item Name" ReadOnly="true">
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Rate" HeaderText="Price" ReadOnly="true">
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:TemplateField HeaderStyle-CssClass="headerStyle" HeaderText="Quantity">
<EditItemTemplate>
<asp:DropDownList ID="ddlqty" runat="server" DataTextField='<%# Bind("qty") %>' AutoPostBack="false" EnableViewState="true">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
<asp:ListItem>4</asp:ListItem>
<asp:ListItem>5</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblqty" runat="server" Text='<%# Bind("qty") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle CssClass="headerStyle" HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-CssClass="headerStyle">
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" Text="Save" ></asp:LinkButton>
<%--<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>--%>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" CommandName="Edit" Text="Change"></asp:LinkButton>
</ItemTemplate>
<HeaderStyle CssClass="headerStyle" />
<ItemStyle HorizontalAlign="Center" Width="30px" Font-Size="Small" />
</asp:TemplateField>
<asp:BoundField DataField="total" HeaderText="Total" ReadOnly="true">
<HeaderStyle HorizontalAlign="Right" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" />
</asp:BoundField>
</Columns>
<EditRowStyle HorizontalAlign="Center" VerticalAlign="Middle" BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" ForeColor="#333333" Font-Bold="True" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" HorizontalAlign="Center" VerticalAlign="Middle" ForeColor="White" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
I had a previous project with me doen by a friend so used his codes.

Display total no of records of gridview in the Footer of Gridview

I have to display total no of records present in the gridview, for information purpose.
I want to show that in Gridview footer as
Total Records is "" records.
Here is the my gridview aspx code
<asp:GridView ID="grdTeacherProfile"
runat="server"
Width="100%"
border="1" Style="border: 1px solid #E5E5E5;"
CellPadding="3" FooterStyle-BackColor="#e3e3e3"
AutoGenerateColumns="false"
AllowPaging="true"
DataKeyNames="Id"
CssClass="hoverTable"
PageSize="10"
ShowFooter="false"
OnPreRender="PreRenderGrid"
HeaderStyle-CssClass="k-grid td"
OnDataBound="grdTeacherProfile_DataBound"
OnPageIndexChanging="grdTeacherProfile_PageIndexChanging"
OnRowDeleting="grdTeacherProfile_RowDeleting"
OnRowCommand="grdTeacherProfile_RowCommand"
EnableSortingAndPagingCallbacks="false"
EmptyDataText="No records found">
<AlternatingRowStyle CssClass="k-alt" />
<Columns>
<asp:TemplateField HeaderText="Select" ItemStyle-Width="5">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" onClick="Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="first_name" HeaderText="First Name" ItemStyle-Width="25" />
<asp:BoundField DataField="last_name" HeaderText="Last Name" ItemStyle-Width="25" />
<asp:BoundField DataField="emailid" HeaderText="Email Id" ItemStyle-Width="25" />
<asp:BoundField DataField="dob" HeaderText="Date of Birth" ItemStyle-Width="20" ApplyFormatInEditMode="true" DataFormatString="{0:d}" />
<asp:BoundField DataField="gender" HeaderText="Gender" ItemStyle-Width="20" />
<asp:BoundField DataField="designation" HeaderText="Designation" ItemStyle-Width="20" />
<asp:BoundField DataField="joining_date" HeaderText="Joining Date" ItemStyle-Width="20" ApplyFormatInEditMode="true" DataFormatString="{0:d}" />
<asp:BoundField DataField="leaving_date" HeaderText="Leaving Date" ItemStyle-Width="20" ApplyFormatInEditMode="true" DataFormatString="{0:d}" />
<asp:BoundField DataField="active" HeaderText="Active" ItemStyle-Width="25" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" AlternateText="Edit" ImageUrl="~/images/edit.png" ToolTip="Edit" runat="server" Width="15" Height="15" CommandName="eEdit" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" />
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" ToolTip="Delete" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle ForeColor="#e3e3e3"
BackColor="#e3e3e3" CssClass="grid-pagi" />
<PagerTemplate>
<table runat="server" id="testTable1" style="width: 100%" class="hoverTable_tbl">
<tr>
<td class="col-md-4 pull-left">
<asp:Label ID="MessageLabel"
Text="Select a page:"
runat="server" />
<asp:LinkButton ID="FirstLB" runat="server" CommandName="Page" CommandArgument="First" ToolTip="First" CssClass="btn-pager btn-default"><<</asp:LinkButton>
<asp:LinkButton ID="PrevLB" runat="server" CommandName="Page" CommandArgument="Prev" ToolTip="Previous" CssClass="btn-pager btn-default"><</asp:LinkButton>
<asp:DropDownList runat="server" ID="PageDropDownList" AutoPostBack="true" EnableViewState="true" OnSelectedIndexChanged="PageDropDownList_SelectedIndexChanged" CssClass="selectpicker form-control-drp"></asp:DropDownList>
<asp:LinkButton ID="NextLB" runat="server" CommandName="Page" CommandArgument="Next" ToolTip="Next" CssClass="btn-pager btn-default">></asp:LinkButton>
<asp:LinkButton ID="LastLB" runat="server" CommandName="Page" CommandArgument="Last" ToolTip="Last" CssClass="btn-pager btn-default">>></asp:LinkButton>
</td>
<td>
<asp:Label ID="lblRecords" runat="server" Text="sss"></asp:Label>
</td>
<td class="col-md-3">
<div>
<div class="pull-left">
<asp:Label ID="PageSizeLabel" CssClass="page-size" runat="server" Text="Select Page Size: "></asp:Label>
<asp:DropDownList ID="ddlPageSize" runat="server" OnSelectedIndexChanged="ddlPageSize_SelectedIndexChanged" AutoPostBack="true" CssClass="selectpicker form-control-drp">
<%-- <asp:ListItem Value="0" Text="0" />--%>
<asp:ListItem Value="1" Text="1" />
<asp:ListItem Value="2" Text="2" />
<asp:ListItem Value="3" Text="3" />
</asp:DropDownList>
</div>
<div>
<asp:Label ID="CurrentPageLabel" CssClass="view" runat="server" />
</div>
</div>
</td>
</tr>
</table>
</PagerTemplate>
<RowStyle />
</asp:GridView>
CS Codebehind:-
public void BindGrid()
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
SqlCommand cmd = new SqlCommand("Select Id, first_name, last_name,emailid, dob, gender, designation, joining_date, leaving_date, active from tbl_teachers_profile Order by Id desc");
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
grdTeacherProfile.DataSource = dt;
grdTeacherProfile.DataBind();
DisablePageDirections();
grdTeacherProfile.BottomPagerRow.Visible = true;
}
}
}
}
Please help
Writing an all new answer since the first one was way too verbose.
Set the ShowFooter="true" on your GridView. Next edit the first TemplateField like this:
<asp:TemplateField HeaderText="Select" ItemStyle-Width="5">
<ItemTemplate>
<asp:CheckBox ID="chkDelete" runat="server" onClick="Check_Click(this)" />
</ItemTemplate>
<FooterTemplate>
Number of records: <%# grdTeacherProfile.Rows.Count %>
</FooterTemplate>
</asp:TemplateField>
And that's all you should need. At least works while I tested.
There should also be some way to span the text to several columns, but didn't have time to test for that..
int RowCount = grdTeacherProfile.Rows.Count;
lblDisplayCount.Text = RowCount.ToString();
Try this code.

Printing an aspx file in Asp.net

I have used the following code to print an HTML DIV Contents & it works fine, but when I am using an Ajax Control in an Aspx page then it gives me an error message, i.e:
"Extender control 'CalendarExtender2' is not a registered extender
control. Extender controls must be registered using
RegisterExtenderControl() before calling RegisterScriptDescriptors().
Parameter name: extenderControl"
Here is my C# code
protected void BtnPrint_Click(object sender, EventArgs e)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
Page pg = new Page();
pg.EnableEventValidation = false;
HtmlForm frm = new HtmlForm();
pg.EnableEventValidation = false;
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(divContent);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("<script>window.print();</script>");
HttpContext.Current.Response.End();
}
Here is my Aspx code
<%# Page Title="" Language="C#" MasterPageFile="~/Masters/TSAMaster.master" AutoEventWireup="true"
EnableEventValidation="false" Theme="skinFiles" CodeFile="AdminHome.aspx.cs"
Inherits="Masters_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<script type="text/javascript">
function ValidateDate() {
isValidDate = ValidateDate();
if (!isValidDate) {
return false;
}
else {
return true;
}
}
function ValidateDate() {
var Fdate = document.getElementById('ctl00_ContentPlaceHolder1_txtFDate').value;
var Tdate = document.getElementById('ctl00_ContentPlaceHolder1_txtTDate').value;
var todaysDate = formatDate(new Date(), 'dd/MM/yyyy');
var isValidDate = true;
var flag;
if (trim(Fdate) != 0 || trim(Tdate) != 0) {
if (!isDate(Fdate, 'dd/MM/yyyy')) {
alert("Please select valid From Date enter into (dd/MM/yyyy) format");
document.getElementById('ctl00_ContentPlaceHolder1_txtFDate').focus();
return false;
}
if (!isDate(Tdate, 'dd/MM/yyyy')) {
alert("Please select valid To Date enter into (dd/MM/yyyy) format ");
document.getElementById('ctl00_ContentPlaceHolder1_txtFDate').focus();
return false;
}
if (((compareDates(Fdate, 'dd/MM/yyyy', Tdate, 'dd/MM/yyyy')) == 1)) {
alert("To date cannot be less than From Date ");
return false;
}
return true;
}
}
function trim(str) {
return str.replace(/^[\s]+/, '').replace(/[\s]+$/, '').replace(/[\s]{2,}/, ' ');
}
</script>
<ajaxToolkit:ToolkitScriptManager runat="Server" EnableScriptGlobalization="true"
EnableScriptLocalization="true" ID="ScriptManager1" />
<center>
<div class="divContainPage" id="divContent" runat="server">
<table id="tblHead" runat="server">
<tr>
<td>
<asp:Label ID="Label3" runat="server" Text="DueDate Report" Font-Bold="True" Font-Names="Verdana"
Font-Size="Large" ForeColor="#C80000"></asp:Label>
<br />
<br />
<table id="tbl1" runat="server" style="width: 823px">
<tr>
<td>
Select Payment Mode:
</td>
<td>
<asp:DropDownList ID="ddlPayMode" runat="server" CssClass="DropDown" Width="85px">
<asp:ListItem>--Select--</asp:ListItem>
<asp:ListItem>Cash</asp:ListItem>
<asp:ListItem>Cheque</asp:ListItem>
</asp:DropDownList>
</td>
<td>
From Date:
</td>
<td>
<asp:TextBox ID="txtFDate" runat="server" Width="110px"></asp:TextBox>
<asp:ImageButton ID="imgCalendar" runat="server" ImageUrl="~/Images/calendar.png"
TabIndex="1" />
<ajaxToolkit:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="txtFDate"
Format="dd/MM/yyyy" PopupPosition="BottomRight" PopupButtonID="imgCalendar" />
</td>
<td>
To Date:
</td>
<td>
<asp:TextBox ID="txtTDate" runat="server" Width="110px"></asp:TextBox>
<asp:ImageButton ID="imgCalendar1" runat="server" ImageUrl="~/Images/calendar.png"
TabIndex="2" />
<ajaxToolkit:CalendarExtender ID="CalendarExtender3" runat="server" TargetControlID="txtTDate"
Format="dd/MM/yyyy" PopupPosition="BottomRight" PopupButtonID="imgCalendar1" />
</td>
<td>
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" OnClientClick="return ValidateDate();" />
</td>
<td>
<asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="btnReset_Click" Width="47px" />
</td>
</tr>
</table>
<table style="width: 600px" runat="server" id="tblone">
<tr>
<td>
<asp:GridView ID="grdStudentInfo" runat="server" SkinID="Professional" DataKeyNames="StudentID"
Width="800px" AllowSorting="True" AutoGenerateColumns="False" BackColor="#DEBA84"
BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
OnSorting="grdStudentInfo_sorting" AllowPaging="True" OnPageIndexChanging="grdStudentInfo_PageIndexChanging"
OnRowCommand="grdStudent_RowCommand">
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<Columns>
<asp:BoundField HeaderText="Name" DataField="FirstandLastName" SortExpression="FirstandLastName">
<ItemStyle HorizontalAlign="left" Width="100px" />
<HeaderStyle HorizontalAlign="left" Width="100px" />
</asp:BoundField>
<asp:BoundField HeaderText="Amount Due" DataField="FirstInstallmentFee" SortExpression="FirstInstallmentFee">
<ItemStyle HorizontalAlign="left" Width="100px" />
<HeaderStyle HorizontalAlign="left" Width="100px" />
</asp:BoundField>
<asp:BoundField HeaderText="Payment Mode" DataField="FirstInsMode" SortExpression="FirstInsMode">
<ItemStyle HorizontalAlign="left" Width="100px" />
<HeaderStyle HorizontalAlign="left" Width="100px" />
</asp:BoundField>
<asp:BoundField HeaderText="Bank Name" DataField="FirstBankName" SortExpression="FirstBankName">
<ItemStyle HorizontalAlign="left" Width="200px" />
<HeaderStyle HorizontalAlign="left" Width="200px" />
</asp:BoundField>
<asp:BoundField HeaderText="Cheque Number" DataField="FirstChequeNumber" SortExpression="FirstChequeNumber">
<ItemStyle HorizontalAlign="left" Width="200px" />
<HeaderStyle HorizontalAlign="left" Width="200px" />
</asp:BoundField>
<asp:BoundField HeaderText="Due Date" DataField="FirstInstallmentDate" SortExpression="FirstInstallmentDate">
<ItemStyle HorizontalAlign="left" Width="200px" />
<HeaderStyle HorizontalAlign="left" Width="200px" />
</asp:BoundField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CommandName="editStudent" Text="Edit"
CommandArgument='<%#Eval("StudentID")%>'></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Width="200px" />
<HeaderStyle HorizontalAlign="Left" Width="200px" />
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</td>
</tr>
</table>
<table id="tbl3" runat="server">
<tr style="height: 30px;">
<td>
<asp:Button ID="btnExport2PDF" runat="server" Text="Export To PDF" OnClick="btnExport2PDF_Click" />
</td>
<td>
<asp:Button ID="btnExport2XLS" runat="server" Text="Export To XLS" OnClick="btnExport2XLS_Click" />
<asp:HiddenField ID="hidSort" runat="server" Value="1" />
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</center>
If I use frm.Controls.Add(tblOne) instead of frm.Controls.Add(divContent) then it works fine because tblone doesn't have an Ajax Control. But divContent has both the table as well as Ajax Controls, and it throws the above exception. I have tried many options like overriding OnInit and OnPreRender but doesn't work for me.
It could be due to the placement of ToolkitScriptManager in your code. See if this resolves your problem:
Error: Extender controls may not be registered before PreRender
Finally i have resolved this problem by using JavaScript code & it works better for me, i would like to thanks for all who gives their valuable time & feedback.
The code is here :
<script>
function Panel1() {
var panel = document.getElementById("<%=printablediv.ClientID %>");
var printWindow = window.open('', '', 'height=400,width=800');
printWindow.document.write('<html><head><title>newTable</title>');
printWindow.document.write('</head><body >');
printWindow.document.write(panel.innerHTML);
printWindow.document.write('</body></html>');
printWindow.document.close();
setTimeout(function() {
printWindow.print();
printWindow.close();
}, 1000);
return false;
}
</script>

Can't display male/female for gender in gridview

I have a data field "Gender" (sql data type - bit).
I have created bound the data with if condition to check true-> male otherwise -> female. But it still does not display.
Here is the aspx and code behind code:The gridview shows true/false instead of male/female:
<%# Page Title="Add User" Language="C#" AutoEventWireup="true" CodeFile="adduser.aspx.cs" Inherits="_Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="style.css" type="text/css" rel="Stylesheet" />
<script type="text/javascript">
function confirmDelete() {
return confirm("Do you want to delete this record?");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<ajax:ToolkitScriptManager ID="toolkit1" runat="server">
</ajax:ToolkitScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table border="0" align="center" cellpadding="2" cellspacing="2" class="maindiv">
<tr><!--Hidden field for EmployeeID reference-->
<td colspan="2"><asp:HiddenField ID="txtHiddenEmpID" Value="0" runat="server" /></td>
</tr>
<tr>
<td>
<span class="asterisk">*</span><asp:Label ID="name" runat="server" Text="Name"></asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmpName" runat="server" CssClass="box"></asp:TextBox>
<asp:RequiredFieldValidator Display="None" ID="RequiredFieldValidator1" ErrorMessage="Name is required!"
EnableClientScript="true" SetFocusOnError="true" runat="server" ControlToValidate="txtEmpName"
CssClass="error_msg"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="NameValidator" runat="server" ErrorMessage="Name can not contain numeric or special characters."
ControlToValidate="txtEmpName" ValidationExpression="^[A-Za-z ]*$" CssClass="error_msg"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<span class="asterisk">*</span><asp:Label ID="Label1" runat="server" Text="Address"></asp:Label>
</td>
<td>
<asp:TextBox ID="addressBox" runat="server" CssClass="box"></asp:TextBox>
<asp:RequiredFieldValidator Display="None" ID="AddressValidator" ErrorMessage="Address is required!"
EnableClientScript="true" SetFocusOnError="true" runat="server" ControlToValidate="addressBox"
CssClass="error_msg"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<span class="asterisk">*</span><asp:Label ID="Label2" runat="server" Text="DOB"></asp:Label>
</td>
<td>
<asp:TextBox ID="dobBox" runat="server" CssClass="dob_cal box" ReadOnly="false" ></asp:TextBox>
<ajax:CalendarExtender ID="CalenderExtender1" TargetControlID="dobBox" Format="dd/MM/yyyy"
runat="server">
</ajax:CalendarExtender>
<asp:RequiredFieldValidator Display="None" ID="dobValidator" ErrorMessage="DOB is required!"
EnableClientScript="true" SetFocusOnError="true" runat="server" ControlToValidate="dobBox"
CssClass="error_msg"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<span class="asterisk">*</span><asp:Label ID="Label3" runat="server" Text="Salary"></asp:Label>
</td>
<td>
<asp:TextBox ID="salaryBox" runat="server" CssClass="box" MaxLength="8" ></asp:TextBox>
<asp:RequiredFieldValidator ID="salaryValidate" runat="server" ControlToValidate="salaryBox"
ErrorMessage="Salary is required!" Display="None" CssClass="error_msg" SetFocusOnError="true"
EnableClientScript="true"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="SalaryValidator" runat="server" ErrorMessage="Salary can contain only numeric values."
Display="None" ControlToValidate="salaryBox" ValidationExpression="^[0-9]*$"
CssClass="error_msg"></asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
<span class="asterisk">*</span><asp:Label ID="gender" runat="server" Text="Gender"></asp:Label>
</td>
<td>
<span>
<asp:RadioButton GroupName="gendergrp" ID="gendermale" runat="server" Text="Male"
Checked="true" /></span><span style="padding-left: 5px;">
<asp:RadioButton GroupName="gendergrp" ID="genderfemale" runat="server" Text="Female"
Checked="false" /></span>
</td>
</tr>
<tr>
<td>
<div style="float: right; margin-right: -70px;">
<asp:Button ID="Button1" runat="server" CssClass="btn" Text="Save" OnClick="Button1_Click" /></div>
</td>
<td>
<div style="float: left; margin-left: 70px;">
<asp:Button ID="CancelBtn" CausesValidation="false" runat="server" CssClass="btn"
Text="Cancel" OnClick="CancelBtn_Click" />
</div>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="lblError" runat="server" CssClass="error_msg"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2">
<asp:ValidationSummary ID="valSum" DisplayMode="BulletList" EnableClientScript="true"
HeaderText="Error!" runat="server" CssClass="error_msg" />
</td>
</tr>
</table>
<!--div for data display-->
<div class="data_display">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataKeyNames="EmployeeID" EmptyDataText="There are no data records to display."
GridLines="Horizontal" BackColor="#CCCCCC" BorderColor="White" Font-Bold="False"
Font-Names="Arial" Font-Size="Medium" ForeColor="#666666"
AllowPaging="True" PageSize="5" PagerSettings-Mode="Numeric"
PagerSettings-Position="Bottom"
onpageindexchanging="GridView1_PageIndexChanging"
>
<Columns>
<%-- <asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="EmpID" runat="server" Value='<%# Eval("EmployeeID") %>' />
</ItemTemplate>
</asp:TemplateField>
--%> <asp:BoundField DataField="EmployeeID" HeaderText="Employee ID"
SortExpression="EmployeeID" Visible="true" ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="EmployeeName" HeaderText="Name" SortExpression="EmployeeName"
ItemStyle-Width="130px" ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" Width="130px" />
</asp:BoundField>
<asp:BoundField DataField="DateOfBirth" HeaderText="DoB" SortExpression="DateOfBirth"
DataFormatString="{0:dd-MM-yyyy}" ItemStyle-Width="100px" ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="Salary" HeaderText="Salary"
SortExpression="Salary">
<ItemStyle HorizontalAlign="Center" Width="90px" />
</asp:BoundField>
<asp:BoundField DataField="Gender" HeaderText="Gender" ItemStyle-Width="90px"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" Width="70px" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="EditBtn" runat="server" Text="Select" CausesValidation="false" OnClick="EditBtn_Click" />
<asp:Button ID="DelBtn" runat="server" Text="Delete" CausesValidation="false" OnClick="DelBtn_Click" OnClientClick="confirmDelete()" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#ffffff" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="Gray" Font-Bold="false" ForeColor="White" />
<PagerStyle BackColor="Gray" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<br />
<span style="font-family: Arial; font-size: small; color: Green; font-weight: bold;">
You are viewing page <%=GridView1.PageIndex + 1%> of <%=GridView1.PageCount%>
</span>
</div>
<div>
<asp:Label ID="lblMessage" runat="server"></asp:Label></div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
**code behind:**
#region GridView Functions
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[4].Text == "True")
{
e.Row.Cells[4].Text = "Male";
}
else
{
e.Row.Cells[4].Text = "Female";
}
}
}
#endregion
The gridview Gender column shows true/false instead of male/female.
Thanks!
You need a TemplateField for this. Assuming Male equates to True, this should work:
<asp:TemplateField HeaderText="Gender" SortExpression="Gender">
<ItemTemplate><%# (Boolean.Parse(Eval("Gender").ToString())) ? "Male" : "Female" %></ItemTemplate>
</asp:TemplateField>

Categories

Resources