Working with Telerik RadGrid - c#

I have a Rad combo box and a 2 RadGrids - grvUser and grvRole
grvUser RadGrid is as follows...
<telerik:RadGrid ID="grvUser" runat="server" EnableEmbeddedSkins="False" Skin="skn_RadGrid" SkinsDir="|CurrentTheme|/" SkinsPath="|CurrentTheme|/"
OnItemCreated="grvUser_ItemCreated" OnItemCommand="grvUser_ItemCommand" OnItemDataBound="grvUser_ItemDataBound" OnNeedDataSource="grvUser_NeedDataSource" GroupHeaderItemStyle-CssClass="rgGroupPanel">
<MasterTableView TableLayout="Fixed" OverrideDataSourceControlSorting="true" NoMasterRecordsText ="No Records Found, Please Refine Search To Display ">
<Columns>
<telerik:GridBoundColumn FilterControlAltText="Filter column column" DataField="UserId"
UniqueName="UserId" HeaderText="User Id" HeaderStyle-Width="120px" FilterControlWidth="70px"
AutoPostBackOnFilter="true">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn FilterControlAltText="Filter column column" DataField="UserName" AllowFiltering="true" ShowFilterIcon="true"
UniqueName="UserName" HeaderText="User Name" HeaderStyle-Width="120px" FilterControlWidth="70px"
AutoPostBackOnFilter="true">
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
grvRole RadGrid is as follows...
<telerik:RadGrid ID="grvRole" runat="server" EnableEmbeddedSkins="False" Skin="skn_RadGrid" SkinsDir="|CurrentTheme|/" SkinsPath="|CurrentTheme|/"
OnItemCreated="grvRole_ItemCreated" OnItemCommand="grvRole_ItemCommand" OnItemDataBound="grvRole_ItemDataBound" OnNeedDataSource="grvRole_NeedDataSource" GroupHeaderItemStyle-CssClass="rgGroupPanel">
<MasterTableView TableLayout="Fixed" OverrideDataSourceControlSorting="true" NoMasterRecordsText ="No Records Found, Please Refine Search To Display ">
<Columns>
<telerik:GridBoundColumn FilterControlAltText="Filter column column" DataField="RoleId"
UniqueName="RoleId" HeaderText="Role Id" HeaderStyle-Width="120px" FilterControlWidth="70px"
AutoPostBackOnFilter="true">
</telerik:GridBoundColumn>
<telerik:GridBoundColumn FilterControlAltText="Filter column column" DataField="RoleName" AllowFiltering="true" ShowFilterIcon="true"
UniqueName="RoleName" HeaderText="Role Name" HeaderStyle-Width="120px" FilterControlWidth="70px"
AutoPostBackOnFilter="true">
</telerik:GridBoundColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
Code for RadComboBox is as follows...
<telerik:RadComboBox ID="ddlType" runat="server" DataValueField="Description"
DataTextField="Description" Text="(Select)" AllowCustomText="True" Width="200px"
OnClientDropDownClosed="onDropDownClosing1" Skin="Default">
<ItemTemplate>
<div onclick="StopPropagation(event)" class="combo-item-template" onmousemove="">
<asp:CheckBox runat="server" ID="chk1" onclick="onStatusChecked(this)" />
<asp:Label runat="server" ID="Label1" AssociatedControlID="chk1">
<%# Eval("Description")%>
</asp:Label>
</div>
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="ChckAll" Text="(Check All)" runat="server" OnClick="checkAllStatus(this)" />
</HeaderTemplate>
</telerik:RadComboBox>
The ddlType RadComboBox contains 2 values. 1 is User and 2 is Role. By default "User" is selected and such that grvUser will be displayed. If the user selects Role, then we need to display grvRole defined in the aspx page.
How can I fire onchange event for RadComboBox and display proper RadGrid either User or Role?
UPDATE
Implementation in jQuery is Ok for me.

Whatever is well conceived is clearly said, And the words to say it
flow with ease.
How to: Show / hide control based on a RadComboBox Value ?
First let's declare a simple RadComboBox with 3 In-line Items :
<telerik:RadComboBox ID="RadComboBox1" runat="server" >
<Items>
<telerik:RadComboBoxItem runat="server" Text="ALL" />
<telerik:RadComboBoxItem runat="server" Text="grvUser" />
<telerik:RadComboBoxItem runat="server" Text="grvRole" />
</Items>
</telerik:RadComboBox>
1/. We now need an event that will be fire every time user choose a "Value".
OnSelectedIndexChanged Will do the trick.
As You talk about a jQuery implementation, here is the documentation RadComboBox event :
Server-side event
Client-side event
NOTE: The SelectedIndexChanged , TextChanged and OnCheckAllCheck events do not fire unless you set the AutoPostBack property to True .
2/.Add the correct event, and some label.
<telerik:RadComboBox ID="RadComboBox1" runat="server" autopostback="True"
OnSelectedIndexChanged="RadComboBox1_SelectedIndexChanged" >
<Items>
<telerik:RadComboBoxItem runat="server" Text="ALL" />
<telerik:RadComboBoxItem runat="server" Text="grvUser" />
<telerik:RadComboBoxItem runat="server" Text="grvRole" />
</Items>
</telerik:RadComboBox>
<asp:Label ID="Label1" runat="server" Text="My Control 1(grvUser)" />
<asp:Label ID="Label2" runat="server" Text="My Control 2(grvRole)" />
3/. Lets hide them in code behind
protected void RadComboBox1_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (e.Text=="ALL")
{
Label1.Visible = true;
Label2.Visible = true;
}
else if (e.Text == "grvUser")
{
Label1.Visible=true;
Label2.Visible=false;
}
else if (e.Text == "grvRole")
{
Label1.Visible = false;
Label2.Visible = true;
}
}
That was a Client-side solution.

Use this to show field-
var agtype = $telerik.$(atCell).text().trim();
if(agtype == ""Guaranty""){{
var masterTableView = sender.get_masterTableView();
var columnIndex = masterTableView.getColumnByUniqueName(""Amount"").get_element().cellIndex;
masterTableView.showColumn(columnIndex);
}}

Related

Getting value of a cell from a GridView on SelectedIndexChanged event of DropDownList

I have a GridView that has data bounded rows. I'm trying to get specific cell value on the SelectedIndexChanged event of DropDownList. My tries are as follows:
string temp= GridView2.SelectedRow.Cells[3].Text;
string temp = ((DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0]).Text;
DataBoundLiteralControl dblc = (DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0];
string temp=dblc.Text;
These all 3 of them returns null.
Moreover, the Control[0] is returning correct value of TemplateFields only, but not DataBound fields.
.aspx
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #d54d7b" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" Width="900px" Font-Names="Segoe UI Light" BorderColor="#DEDEDE">
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="80" />
<asp:BoundField DataField="Vacancies" HeaderText="Vacancies" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Detail">
<ItemTemplate>
<asp:BoundField DataField="Date" HeaderText="Date" ItemStyle-Width="80" />
<asp:BoundField DataField="Time" HeaderText="Time" ItemStyle-Width="80" />
</Columns>
Problem you are probably facing is that, GridView1 hasn't been bounded yet.. that is the reason why Control[0] is returning correct value of TemplateFields but cells in the gridview returns null.
You can do the following
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
/// send value to filter or bind gridView1
/// bind gridvew
string temp = GridView1.Rows[0].Cells[3].Text;
/// or any code to get values from GridView Cell
}
I Converted all <asp:BoundFields> to <asp:TemplateField> and it looked like this:
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #009C0D" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" CssClass="test"
HtmlEncode="true"
Font-Names="Segoe UI Light" BorderColor="#DEDEDE" >
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:TemplateField HeaderText="Description" ControlStyle-Width="250px" ><ItemTemplate> <asp:LinkButton ID= "Description" PostBackUrl='<%# Eval("Description", "~/{0}.aspx") %>' Text='<%# Eval("Description")%>' runat="server" ></asp:LinkButton> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Vacancies"><ItemTemplate> <asp:Label ID="Vacancies" Text='<%# Eval("Vacancies")%>' runat="server" ></asp:Label> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Detail"><ItemTemplate><asp:Label ID="City" Text='<%# Eval("City")%>' runat="server" ></asp:Label> <div style="font-size:10px"> <asp:Label ID="Label1" Text='<%# Eval("DateDay")%>' runat="server" ></asp:Label> </div> </ItemTemplate></asp:TemplateField>
//and others
</Columns>
</asp:GridView>
And get specific value by entering this code behind DropDownList:
if (dropdown.SelectedIndex != -1)
{
ListItem mySelectedItem = (from ListItem li in dropdown.Items where li.Selected == true select li).First();
foreach (GridViewRow rw in GridView2.Rows)
{
Label tv = (Label)rw.Cells[3].FindControl("City");
if (tv.Text.IndexOf(mySelectedItem.Text) != -1)
{
rw.Visible = true;
}
else
rw.Visible = false;
}
}

How to multiply textbox value using javascript?

<asp:GridView ID="GVFeedType" runat="server" Style="margin-bottom: 6px" BorderColor="#BDBDBD"
CssClass="center" Width="500px" AutoGenerateColumns="false">
<EmptyDataTemplate>
No Records found</EmptyDataTemplate>
<Columns>
<asp:BoundField HeaderText="SNo" DataField="SNo" ItemStyle-Width="50px" />
<asp:BoundField HeaderText="Feed Type" DataField="FeedType" ItemStyle-Width="200px" />
<asp:TemplateField HeaderText="Rate/Kg" ItemStyle-Width="80px" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:TextBox ID="txtrate" runat="server" Width="100px" OnTextChanged="txtrate_TextChanged"
AutoPostBack="true" />
<asp:RequiredFieldValidator ID="RFVrecdate1" runat="server" ControlToValidate="txtrate"
Display="None" ErrorMessage="Must Enter Rate" ValidationGroup="duereport"></asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate/50 Kg" ItemStyle-Width="80px">
<ItemTemplate>
<asp:Label ID="lbl50kg" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I tried this code..
protected void txtrate_TextChanged(object sender, EventArgs e)
{
GridViewRow currentRow = (GridViewRow)(sender as TextBox).Parent.Parent;
float rate = 0;
float kgrate50 = 50;
rate = Convert.ToSingle((sender as TextBox).Text.Trim());
kgrate50 = rate * kgrate50;
(currentRow.Cells[3].FindControl("lbl50kg") as Label).Text = kgrate50.ToString();
GVFeedType.Rows[currentRow.RowIndex + 1].Cells[2].FindControl("txtrate").Focus();
}
This code is fine ,Tab not working...
i have a textbox in a grid view control,when i enter some value like 2,3,4 ..then it multiply with 50 ...and it shows output in lable control..here label also in a gridview..how can i solve it..please help me..
I would add CSs class to text box
<asp:TextBox ID="txtrate" runat="server" CssClass="TextBoxToHandle" Width="100px" OnTextChanged="txtrate_TextChanged"
AutoPostBack="true" />
Since using tab throw focusout event you need to subscribe to it
$(function(){
$(".TextBoxToHandle").focusout(function(){
//Do your code here this would be element which you focus left
});
})

Why is Gridview footer adding an extra column?

Can't believe I have to ask this - you'd think such a basic feature would be straightforward to implement, but I'm having trouble creating a footer for a Gridview. I've checked out various tutorials and other questions, such as here, and here and here, but am still encountering difficulties.
The problem is in displaying the footer properly (i.e. without adding an extra empty column). From what I gather, you need to put the FooterTemplate inside a TemplateField tag or it won't work - at least it wouldn't compile for me. If I insert this after the BoundFields columns then it adds an extra column which is not desirable.
<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="false" AllowSorting="true"
CellPadding="3" HorizontalAlign="Center" GridLines="both" CssClass="dataTable1"
OnRowDataBound="Colour_Columns" Caption="PARTIAL COMPARE" ShowFooter="true">
<HeaderStyle BackColor="Black" ForeColor="AntiqueWhite" Height="30" CssClass="header" />
<FooterStyle BackColor="Black" ForeColor="AntiqueWhite" Height="30" CssClass="footer" />
<Columns>
<asp:BoundField DataField="FOLDER" HeaderText="Location" />
<asp:BoundField DataField="FILE" HeaderText="File" />
<asp:BoundField DataField="CHECKSUM" HeaderText="Checksum" Visible="false" />
<asp:BoundField DataField="STATUS" HeaderText="Status" />
<asp:BoundField DataField="DATE" HeaderText="Date" Visible="false" />
<asp:TemplateField>
<FooterTemplate>
<asp:Button ID="UpdateButton" runat="server" Text="UPDATE" CssClass="updateButton" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Similarly, if I put it before the BoundFields it adds an extra column on the left. If I try to put all the BoundFields under the TemplateField it won't compile.
How do I add the footer to the gridview without creating an extra column? Also, while we're at it, how can I set its colspan to 1? (It's only going to have the one Update button in it, so no need for three columns in the footer.)
Colour-Scheme method:
protected void Colour_Columns(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[3].Text == "Match")
e.Row.BackColor = Color.Lime;
if (e.Row.Cells[3].Text == "Mismatch")
e.Row.BackColor = Color.Gold;
if (e.Row.Cells[3].Text == "New File")
e.Row.BackColor = Color.PeachPuff;
}
}
This method does not seem to recognize ItemTemplate values...
Try using template field only for the last column and in that column you can specify the ItemTemplate and FooterTemplate. Try the code below.
<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="false" AllowSorting="true"
CellPadding="3" HorizontalAlign="Center" GridLines="both" CssClass="dataTable1"
OnRowDataBound="Colour_Columns" Caption="PARTIAL COMPARE" ShowFooter="true">
<HeaderStyle BackColor="Black" ForeColor="AntiqueWhite" Height="30" CssClass="header" />
<FooterStyle BackColor="Black" ForeColor="AntiqueWhite" Height="30" CssClass="footer" />
<Columns>
<asp:BoundField DataField="FOLDER" HeaderText="Location" />
<asp:BoundField DataField="FILE" HeaderText="File" />
<asp:BoundField DataField="CHECKSUM" HeaderText="Checksum" Visible="false" />
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="StatusLabel" runat="server" Text='<%# Eval("STATUS") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="UpdateButton" runat="server" Text="UPDATE" CssClass="updateButton" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DATE" HeaderText="Date" Visible="false" />
</Columns>
</asp:GridView>
I changed the Cs file to read the value from the template field. Please recopy the ASPX to becouse I changed it too by adding an ID to the Label
CS:
protected void Colour_Columns(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label StatusLabel = e.Row.FindControl("StatusLabel") as Label;
if (StatusLabel.Text == "Match")
e.Row.BackColor = Color.Lime;
if (StatusLabel.Text == "Mismatch")
e.Row.BackColor = Color.Gold;
if (StatusLabel.Text == "New File")
e.Row.BackColor = Color.PeachPuff;
}
}
You shouldn't use FooterTemplate with BoundField. Footer templates are meant to be used in conjunction with TemplateField.Additionally footer templates are applied per column this is done so you can aggregate totals at the bottom of the gridview in cases where you have numeric data.
Here's an example of using template fields with a footer field in the first column, you can change this as required to suit your needs:
ASPX:
<asp:GridView ID="gridview1" runat="server" AutoGenerateColumns="false" ShowFooter="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFolder" runat="server" Text='<%# Eval("FOLDER") %>' />
</ItemTemplate>
<FooterTemplate>
Footer content displayed under FOLDER, notice no extra column!
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFile" runat="server" Text='<%# Eval("FILE") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblCheck" runat="server" Text='<%# Eval("CHECKSUM") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Result:
Alternatively, you can stick with using BoundFields and add the footer dynamically in code:
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
var footer = new Label();
footer.Text = "Footer content";
//Footer will be displayed under the *first* column
e.Row.Cells[0].Controls.Add(footer);
}
}
How to code this form:
 
PURCHASE ORDER MASTER
    [lblPONumberH]                       
PO Number ://here is textBox //RequireField                  
PO Date : //here istextbox with Calender extender                
Vendor: //here is dropdown
                       Created By ://here is textbox
save//Button Cancel//Button
GridView
                               
Item Description Budget Number Quantity UOM Price
Databound DataBound DataBound DataBound DataBound Edit & Del btn
in footer style
txtItemDescription ddlBnumber txtQuantity ddlUOM txtPrice AddBtn

make Row in gridview asp.net clickable?

I create gridview and remove the select button to make all row clickable but I want to redirect the user for selected item detail
Note: I remover the CommandField select Visible="False"
int rowCount = 0;
protected void gv_TasksProjectForUser_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//var taskID = gv_TasksProjectForUser.SelectedDataKey.Value;
e.Row.Attributes.Add("onclick", "location='TaskDetail.aspx?taskID=" + e.Row.RowIndex + "'");
e.Row.Attributes.Add("onmouseover", "JavaScript:this.style.cursor='pointer';");
}
rowCount++;
}
I have made this with Item Templates.
What you have to do is remove the property AutogenerateColums and add them manually with objects and item templates, on those add one that could be a button.
Later on the code Behind add a event to handle the button click, on that event you can do the response.redirect to another page.
<asp:GridView ID="userGrid" runat="server" CssClass="AdminGrid"
AllowPaging="True" AutoGenerateColumns="False" PageSize="11">
<Columns>
<asp:BoundField DataField="ApplicationId" Visible="False" />
<asp:BoundField DataField="UserName" Visible="False" />
<asp:TemplateField >
<HeaderTemplate>
<asp:Label ID="lblEmail" Text="E-Mail" runat="server" CssClass = "HeaderLabel" meta:resourcekey="lblEmail"></asp:Label>
<asp:ImageButton ID="imgSortEMail" runat="server" ImageUrl="~/Images/normal.gif" OnClick="SortGrid" CommandArgument="EMail" CssClass="SortButton" ToolTip="Click here to Order" />
</HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="lnkEMail" runat="server" CssClass="EmailLinkButton" Text='<%# FormatGridTextDisplay(DataBinder.Eval(Container.DataItem, "EMail")) %>' ToolTip='<%# DataBinder.Eval(Container.DataItem, "EMail") %>' NavigateUrl='<%# DataBinder.Eval(Container.DataItem, "EMail","mailto:{0}") %>' ></asp:HyperLink>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="OverFlowLeftAligned" />
</asp:TemplateField>
<asp:TemplateField >
<HeaderTemplate>
<asp:Label ID="lblSalonUser" Text="Salon User" runat="server" CssClass = "HeaderLabel" meta:resourcekey="lblSalonUser"></asp:Label>
<asp:ImageButton ID="imgSortIsSalonUser" runat="server" ImageUrl="~/Images/normal.gif" OnClick="SortGrid" CommandArgument="IsSalonUser" CssClass="SortButton" ToolTip="Click here to Order" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSalonUser" runat="server" Checked='<%# DataBinder.Eval(Container.DataItem, "IsSalonUser") %>' onclick="javascript:if (this.checked==true) this.checked=false; else this.checked=true;"/>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="CenterAligned" />
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" Text="Editar" CssClass="GridButton" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "UserName")%> ' OnClick="btnEdit_Click" meta:resourcekey="btnEdit"/>
</ItemTemplate>
<HeaderStyle CssClass="OverFlowStringField" />
<ItemStyle CssClass="CenterAligned" />
</asp:TemplateField>
</Columns>
</asp:GridView>
There You can see that i add a few types of items template, the most important is the btnEdit, on that one there are 2 important properies, one is the CommandArgument where you send the values to redirect to the page and the other is the event OnClick that is the one that will handle the click for the button.
Protected void btnEdit_Click(Object sender , System.EventArgs e ){
Button clickedButton = (sender)Button;
String() argumentsSend = clickedButton.CommandArgument.ToString().Split("|");
String backParameters;
Response.Redirect(String.Concat("RedirectPage.aspx?user=", Server.UrlEncode(argumentsSend(0)), "&company=", Server.UrlEncode(argumentsSend(1)), True);
}
I took this code from VB and change it to c# with a compiler, it may have errors, but that's the idea.
A easyest way is to use a link button or an hipperlink on the template of the grid, that eay you may no need to go to the code file.

Filter the GridView Data based on Checkbox which is outside of GridView?

I have 5 check box on my page and a Grid view with Template Field, I am not using any bond field on page load I am binding the grid with all data of a table, I want to filter the data based on the check box check.
suppose: I have check box like A B C D. All check box are out side of Grid view. When user checked the check box A, then in Grid view, check box A related data should show, like wise for B C and D.
how do that?, Some one please give some example code and bit logic.
It would be great if I'll be able to filter the gridview without any postback.
Grid:
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" CellPadding="3">
<Columns>
<asp:TemplateField HeaderText="ID" SortExpression="ID">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%#Eval("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discription" SortExpression="Discription">
<ItemTemplate>
<asp:Label ID="lblDiscription" runat="server" Text='<%#Eval("Discription") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address" SortExpression="Address">
<ItemTemplate>
<asp:Label ID="lblAddress" runat="server" Text='<%#Eval("Address") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Binding the Grid:
TestPageDao page1Dao = new TestPageDao ();
if (!IsPostBack)
{
IList<TestDAO> TestDAO = page1Dao.GetAlldata();
GridView1.DataSource = TestDAO;
GridView1.DataBind();
}
I tried Filter gridview or http://forums.asp.net/p/1034014/2904713.aspx
If you want to avoid postback, uses jQuery like here:
http://jquerybyexample.blogspot.com/2012/04/how-to-filter-gridview-records-using.html
An alternative is AJAX, but at the end of the story it is a postback-like approach.
Finally using postback you can do it in several ways by dynamically setting the GridView filter before the GridView loads. This can be achieved with the Page load event, the OnSelecting of the associated datasource (if any), or similar.
Here it is an extraction of the aspx:
<asp:CheckBox ID="CheckBox1" runat="server" Text="A" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="B" />
<asp:CheckBox ID="CheckBox3" runat="server" Text="C" />
<asp:CheckBox ID="CheckBox4" runat="server" Text="D" />
<hr />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
DataSourceID="sqlDataSourceGridView" AutoGenerateColumns="False"
CssClass="GridViewStyle" GridLines="None" Width="650px" >
<Columns>
<asp:BoundField DataField="CompanyName" HeaderText="Company" ItemStyle-Width="200px" />
<asp:BoundField DataField="ContactName" HeaderText="Name" ItemStyle-Width="125px"/>
<asp:BoundField DataField="City" HeaderText="city" ItemStyle-Width="125px" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="125px" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceGridView" runat="server"
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>"
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [City], [Country] FROM [Customers]"
OnSelecting="SqlDataSourceGridView_Selecting">
<FilterParameters>
<asp:ControlParameter ControlID="checkbox1" Name="CompanyName" PropertyName="Checked" ConvertEmptyStringToNull="false" />
</FilterParameters>
</asp:SqlDataSource>
Note the OnSelecting event and note that there isn't any filter preset.
Now in the code behind set dynamically the filter:
protected void SqlDataSourceGridView_Selecting(object sender, SqlDataSourceSelectingEventArgs e) {
SqlDataSourceGridView.FilterExpression = string.Empty;
if (CheckBox1.Checked) {
SqlDataSourceGridView.FilterExpression += "(CompanyName=1)";
}
if (CheckBox2.Checked) {
if (!string.IsNullOrEmpty(SqlDataSourceGridView.FilterExpression)) SqlDataSourceGridView.FilterExpression += " OR ";
SqlDataSourceGridView.FilterExpression += "(B=1)";
}
if (CheckBox3.Checked) {
if (!string.IsNullOrEmpty(SqlDataSourceGridView.FilterExpression)) SqlDataSourceGridView.FilterExpression += " OR ";
SqlDataSourceGridView.FilterExpression += "(C=1)";
}
if (CheckBox4.Checked) {
if (!string.IsNullOrEmpty(SqlDataSourceGridView.FilterExpression)) SqlDataSourceGridView.FilterExpression += " OR ";
SqlDataSourceGridView.FilterExpression += "(D=1)";
}
}
If you don't like the OnSelecting event, you can do the same in the PageLoad:
protected void Page_Load(object sender, EventArgs e) {
// here same code of above
// . . .
}
I didn't test it so verify minor errors.

Categories