how to filtering Gridview data - c#

Gridview contains 100 customer, each page 10 customer, how to filter Alphabatically;
If an user clicks A, then list out all customer names that starts with A
Please help.

If you're using an SqlDataSource, you can specify a parameter in the SelectCommand, e.g.
SelectCommand="SELECT * FROM [Genre] WHERE [Name] LIKE #FirstLetter+'%'"
You will have to add the parameter within the , e.g.
<SelectParameters>
<asp:Parameter Name="FirstLetter" Type="String" />
</SelectParameters>
In your code behind, you can set the value of the parameter, e.g.
SqlDataSource1.SelectParameters["FirstLetter"].DefaultValue = filterletter;

The Faster and jQuery Approach is mentioned in this link
$(document).ready(function() {
$('#<%=lblNoRecords.ClientID%>').css('display','none');
$('.links').click(function(e)
{
$('#<%=lblNoRecords.ClientID%>').css('display','none');
var lnkText = $(this).text().toLowerCase();
var iCounter = 0;
$("#<%=gdRows.ClientID%> tr:has(td)").each(function() {
var cell = $(this).find("td:eq(1)").text().toLowerCase();
if(lnkText != 'all')
{
if(cell.indexOf(lnkText) != 0)
{
$(this).css('display','none');
}
else
{
$(this).css('display','');
iCounter++;
}
}
else
{
$(this).css('display','');
iCounter++;
}
});
if(iCounter == 0)
{
$('#<%=lblNoRecords.ClientID%>').css('display','');
}
e.preventDefault();
});
});

Approach #1
ASPX markup:
<asp:Repeater ID="rptAlpha" runat="server" OnItemCommand="rptAlpha_ItemCommand">
<ItemTemplate>
<asp:LinkButton ID="lbAlpha" runat="server"
CommandArgument='<%# Container.DataItem.ToString() %>'><%#Container.DataItem.ToString() %></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1">
</asp:GridView>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
OldValuesParameterFormatString="original_{0}"
OnSelecting="ObjectDataSource1_Selecting" SelectMethod="Load" TypeName="Your.TypeName.Here">
<SelectParameters>
<asp:Parameter Name="Filter" Type="Object" />
</SelectParameters>
</asp:ObjectDataSource>
C# code
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
BindAlphaRepeater();
}
private void BindAlphaRepeater()
{
string[] alphabet = {"a", "b", "c", "d", "e" };
rptAlpha.DataSource = alphabet;
rptAlpha.DataBind();
}
protected void rptAlpha_ItemCommand(object source, RepeaterCommandEventArgs e)
{
string filterleter = e.CommandArgument as string;
if (filterleter == null)
return;
ViewState["filterletter"] = filterleter;
GridView1.DataBind();
}
protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
// This is designed to return null, you might want to change it to a default value
e.InputParameters["Filter"] = ViewState["filterletter"] as string
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("Paging click");
GridView1.DataBind();
}
Explanation:
User a repeater to bind the alphabets and use OnItemCommand of that Repeatet to fetch data and bind the grid view based on selected alphabet.
Approach #2
You can have 26 buttons on top of gridview + one button for All on top of the gridview.
For all 26 buttons you can have common method like buttonAPLHA_Click and based on sender.tag you can filter the data of the gridview.
e.g inside your buttonAPLHA_Click you can have.
GridView.datasource = GetDataByAplha(Sender.Tag.Tostring());
Hope you get what I want to explain.

use this sample query..
string query = "select from tbl_name where name like '%" + dropdownlist.SelectedValue + "'";

Related

Can't set dropdown list selected item

I have a DropDown list on an ASP.Net web page. I'm trying to set its SelectedValue` on page load. I'm using this page as a reference. Here's my code:
<asp:DropDownList runat="server" ID="ddlType" DataSourceID="sdsType" DataTextField="Name" DataValueField="AssetTypeID" />
<asp:SqlDataSource runat="server" ID="sdsType" ConnectionString='<%$ ConnectionStrings:SystemManagement %>' SelectCommand="SELECT AssetTypeID, [Name] FROM AssetType UNION SELECT 0, '' ORDER BY [Name]" SelectCommandType="Text" />
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
if (Request.QueryString["searchtype"] != null)
{
ddlType.SelectedValue = ddlType.Items.FindByText(Request.QueryString["searchtype"]).Value;
ddlType.SelectedValue = "1";
}
}
else
{
}
}
The first line that sets the SelectedValue will give me a Null Reference Exception and if I inspect the ddlType it has no Items. However, if I comment out the first line setting the SelectedValue and set it using the second line (just hard coding the value) it works. What's going on?
You can use the OnDataBound event to do your current logic
/*Note the addition of "OnDataBound" */
<asp:DropDownList runat="server"
ID="ddlType"
DataSourceID="sdsType"
DataTextField="Name"
DataValueField="AssetTypeID"
OnDataBound="ddlType_DataBound"
/>
<asp:SqlDataSource runat="server" ID="sdsType" ConnectionString='<%$ ConnectionStrings:SystemManagement %>' SelectCommand="SELECT AssetTypeID, [Name] FROM AssetType UNION SELECT 0, '' ORDER BY [Name]" SelectCommandType="Text" />
protected void ddlType_DataBound(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
if (Request.QueryString["searchtype"] != null)
{
ddlType.SelectedValue = ddlType.Items.FindByText(Request.QueryString["searchtype"]).Value;
ddlType.SelectedValue = "1";
}
}
else
{
}
}
When you are trying to set the value for ddlType, the DataSource is not yet loaded to the DropDown. If you check the debugger, the ddlType.Items property will show you that it currently has no items, which explains the NullReference exception.
Try to call ddlType.DataBind() before to ensure that ddlType.Items has the items from the database.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
ddlType.DataBind(); // Load data from DataSource
if (Request.QueryString["searchtype"] != null)
{
ddlType.SelectedValue = ddlType.Items.FindByText(Request.QueryString["searchtype"]).Value;
ddlType.SelectedValue = "1";
}
}
else
{
}
}
Make sure to have the ddlType.DataBind() inside the if(!Page.IsPostBack) condition, to avoid loading the data from the database on every PostBack.

Getting value from dropdown in gridview

i am trying to make a "clock in / out site" and one of the functions is for the user to edit old clock ins/outs. i have added a dropdown with 2 values "IND" and "UD". How do i get these values out, and send them to my "CHECKIN" sql value. I hope you know what iam trying to explain.
this is what it looks like:
The Dropdown:
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem Selected="True">Ind</asp:ListItem>
<asp:ListItem Value="UD">Ud</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
what ive tried:
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string val = row.Cells[3].ToString();
SqlDataSource1.SelectParameters.Add("CHECKEDIN", val);
}
and aswell as:
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)GridView1.FindControl("DropDownList2");
string val = ddl.SelectedValue;
SqlDataSource1.SelectParameters.Add("CHECKEDIN", val);
}
Both of these return "null" tho
Use RowDataBound event of GridView.
Code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow
&& GridView1.EditIndex == e.Row.RowIndex)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList2");
string val = ddl.SelectedValue.ToString();
SqlDataSource1.SelectParameters.Add("CHECKEDIN", val);
}
}
You can cast the sender back to a DropDownlist and get the selected value
DropDownList dropDownList = sender as DropDownList;
string val = dropDownList.SelectedValue;
But how will you know with this method which row the DropDownList belongs to?
You can use a trick for that, like abusing the CSS class to get the correct row number.
<asp:DropDownList ID="DropDownList2" runat="server" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" AutoPostBack="true" CssClass='<%# Container.DataItemIndex %>'>
And get the row number in code behind.
int rowNumber = Convert.ToInt32(dropDownList.CssClass);

Display different Gridviews with a Dropdownlist onchange

I want to show different Gridviews when I select values from a dropdownlist.I use Visible="False" property to gridviews and I want to show only one on every value updated.
Example: when I select the Value "Points" I want to show GridView1 and when I select Names I want to show "GridView2". This is my ASP:
<asp:DropDownList ID="Stats_Ddl" runat="server" AutoPostBack="True" OnSelectedIndexChanged="Stats_Ddl_IndexChanged" >
<asp:ListItem>POINTS</asp:ListItem>
<asp:ListItem>NAMES</asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" Visible="False"> blahblahblah1</asp:GridView>
<asp:GridView ID="GridView2" runat="server" Visible="False">blahblahblah12</asp:GridView>
and c# is:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Stats_Ddl_IndexChanged(object sender, EventArgs e)
{
}
Any suggestions for c# code? thanks...
Hi inside event SelectedIndexChanged
you should put for example
If(Ddl.SelectedValue == "1"){
GridView1.Visible = true;
GridView2.Visible = false;
}else{
GridView1.Visible = false;
GridView2.Visible = true;
}
i see that you have a ListItem don't forget give to a value to property "Value" for example
Point = 1
Name = 2
You can use SelectedItem.Text property of DropDownList to branch
protected void Stats_Ddl_IndexChanged(object sender, EventArgs e)
{
if(Stats_Ddl.SelectedItem.Text == "POINTS")
GridView1.Visible = true;
else
if(Stats_Ddl.SelectedItem.Text == "NAMES")
GridView2.Visible = true;
}

My RadioButtonList won't append Query String or show selected value after Postback - C# & .Net

I have 2 issues. On an aspx page, I have 3 RadioButtonLists (aka RBL)that gets each of their data from a database table. Upon selection on any RBL, a postback occurs to the same page and the value of that specific RBL gets entered into the querystring, that a ListView is looking for, to filter out products based on the querystring. The List View works fine when it reads the querystring an properly filters the list down.
Issue 1 - On postback, the value that you selected from any of the 3 RBL's, doesn't get selected when the page loads. So all my RBL's don't have any value, even if I have a default value set on the page. How do I get my page to reload with the values selected in the RBL's that you've chosen?
Issue 2 - If you make a selection on any of the other 2 RBL's, instead of updating the querystring, it wipes out the first value when it posts back again. So if you pick something in RBL-1, it posts back with that specific field updated in the querystring, but then if you pick something in RBL-2, it posts back but only the value from RBL-2, and wipes out the value that you just picked from RBL-1. How can I get my page to load, while keeping any of your prior selections in the querystring?
ASPX code:
<p>Normally Open or Closed:<asp:RadioButtonList ID="RadioButtonList1" runat="server" EnableViewState="true"
AutoPostBack="true" DataSourceID="NormalitySDS" DataTextField="Op"
DataValueField="Op" onselectedindexchanged="RadioButtonAllLists_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:SqlDataSource ID="NormalitySDS" runat="server"
ConnectionString="<%$ 005 %>"
SelectCommand="SELECT DISTINCT [Op] FROM [Matrix] ORDER BY [Op]">
</asp:SqlDataSource>
</p>
<p>Sizes:<asp:RadioButtonList ID="RadioButtonList2" runat="server" EnableViewState="true"
AutoPostBack="True" DataSourceID="SizesSDS" DataTextField="SIZE" RepeatColumns="2"
DataValueField="SIZE" onselectedindexchanged="RadioButtonAllLists_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:SqlDataSource ID="SizesSDS" runat="server"
ConnectionString="<%$ 005 %>"
SelectCommand="SELECT DISTINCT [SIZE] FROM [Matrix] ORDER BY [SIZE]">
</asp:SqlDataSource>
</p>
<p>Body:<asp:RadioButtonList ID="RadioButtonList3" runat="server" EnableViewState="true"
AutoPostBack="True" DataSourceID="BodySDS" DataTextField="Body"
DataValueField="Body" OnSelectedIndexChanged="RadioButtonAllLists_SelectedIndexChanged">
</asp:RadioButtonList>
<asp:SqlDataSource ID="BodySDS" runat="server"
ConnectionString="<%$ 005 %>"
SelectCommand="SELECT DISTINCT [Body] FROM [Matrix] ORDER BY [Body]">
</asp:SqlDataSource>
<SelectParameters>
<asp:QueryStringParameter DefaultValue="NC" Name="Op" QueryStringField="Op" Type="String" />
<asp:QueryStringParameter DefaultValue="0.25" Name="Sz" QueryStringField="Sz" Type="String" />
<asp:QueryStringParameter DefaultValue="304" Name="Body" QueryStringField="Body" Type="String" />
</SelectParameters>
Code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Configurator
{
public partial class Product_Config_Full_wQuery : System.Web.UI.Page
{
string BaseUrl = "/Product_Config_Full_wQuery.aspx";
string op;
string op2;
string sz;
string body;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
op = (Server.UrlDecode(Request.QueryString["op"] ));
RadioButtonList1.SelectedIndex = op2;
RadioButtonList1.DataBind();
sz = Server.UrlDecode(Request.QueryString["sz"]);
body = Server.UrlDecode(Request.QueryString["body"]);
}
}
// Combining all actions into a single protected-event
protected void RadioButtonAllLists_SelectedIndexChanged(object sender, EventArgs e)
{
op = RadioButtonList1.SelectedValue.ToString();
sz = RadioButtonList2.SelectedValue.ToString();
body = RadioButtonList3.SelectedValue.ToString();
if (op != null)
{
BaseUrl += "?Op=" + op + "&";
}
//else op = "NC";
if (sz != null)
{
BaseUrl += "Sz=" + sz + "&";
}
if (body != null)
{
BaseUrl += "Body=" + body + "&";
}
Response.Redirect(string.Format(BaseUrl, Server.UrlEncode(op), Server.UrlEncode(sz), Server.UrlEncode(body)));
}
Since you're dynamically setting the values inside the radio button list, the values the page would be setting those controls to aren't actually there on postback (page lifecycle would be trying to set values into those controls before your data sources would actually retrieve the possible values and add those items into the control itself).
Also, stop using the querystring to hold postback values - if you really need to, set up some HiddenFields to hold information, those will persist through postbacks and you won't have to worry about odd querystring issues
I figured I'd post up the code, I used to fix my own issue. Based on about 10 different website sources and some trial/error.
public partial class Bla zay blaz : System.Web.UI.Page
{
string BaseUrl = "/blahblah.aspx?";
string op;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
op = Server.HtmlDecode(Request.QueryString["op"]);
if (op == null)
op = "A";
RadioButtonList1.SelectedValue = op;
}
protected void RadioButtonChanged(object sender, EventArgs e)
{
op = RadioButtonList1.SelectedValue;
if (op == null)
op = "NC";
if (op != "A")
BaseUrl += "Op=" + op + "&";
Response.Redirect(string.Format(BaseUrl, Server.HtmlEncode(op));
}
}

Binding RowCommand to fire when any cell in a row is clicked

My GridView basically displays a summarized version of data in the database.
What I want to do is set it up so that when you click anywhere in a row in the GridView, it should execute a set procedure that'll hide the panel that contains the GridView and display a panel that will show you the details of the item you clicked.
<asp:Panel runat="server" ID="pnlList">
<div class="rightalign">
<asp:Label runat="server" ID="lblCount"></asp:Label>
</div>
<asp:GridView runat="server" ID="gvItems" DataKeyNames="mailid"
AutoGenerateColumns="false" onrowdatabound="gvItems_RowDataBound"
Width="100%" OnSelectedIndexChanged="gvItems_SelectedIndexChanged">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkSelect" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="lblStatus" Text='<%# DataBinder.Eval(Container.DataItem, "status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="firstname" HeaderText="From" SortExpression="firstname" />
<asp:BoundField DataField="datesent" HeaderText="Date" SortExpression="datesent" DataFormatString="{0:yyyy/MM/dd HH:mm}" />
<asp:BoundField DataField="subject" HeaderText="Subject" SortExpression="subject" />
</Columns>
</asp:GridView>
</asp:Panel>
<asp:Panel runat="server" ID="pnlMail">
<p>From: <asp:Label runat="server" ID="lblFrom"></asp:Label><br />
Sent On: <asp:Label runat="server" ID="lblDate"></asp:Label><br />
Subject: <asp:Label runat="server" ID="lblSubject"></asp:Label></p>
<p><asp:Label runat="server" ID="lblMessage"></asp:Label></p>
</asp:Panel>
I figured I'd use the SelectedIndexChanged event, but I'm not sure how to actually make it fire off clicks on the cells.
Here's the code I've got:
protected void gvItems_SelectedIndexChanged(object sender, EventArgs e)
{
int index = gvItems.SelectedIndex;
string mailid = gvItems.DataKeys[index].Value.ToString();
getMailDetail(mailid);
pnlMail.Visible = true;
}
protected void getMailDetail(string id)
{
int mailid = int.Parse(id);
MySqlContext db = new MySqlContext();
string sql = "select m.datesent, m.subject, m.message, u.firstname, u.lastname from mail m inner join users u on m.senderid = u.userid where m.mailid = #id";
List<MySqlParameter> args = new List<MySqlParameter>();
args.Add(new MySqlParameter() { ParameterName = "#id", MySqlDbType = MySqlDbType.Int32, Value = mailid });
MySqlDataReader dr = db.getReader(sql, args);
if (dr.HasRows)
{
dr.Read();
lblFrom.Text = (string)dr["firstname"] + " " + (string)dr["lastname"];
lblDate.Text = (string)dr["datesent"];
lblSubject.Text = (string)dr["subject"];
lblMessage.Text = (string)dr["message"];
}
dr.Close();
}
How can I make clicks on the cells in a row fire an event that'll do the work I need done?
Any help will be appreciated!
I can see two possible solutions here. First - handle click on the row on client side, send Ajax request to some HttpHandler that will return you necessary mail details, and display the returned info. Steps to achieve this:
Assign a client side handler too row click:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "showMailDetails(" + DataBinder.Eval(e.Row.DataItem, "id") + ")";
}
}
And define the client side function:
function showMailDetails(mailId) {
$.get(
url: 'url to HttpHandler here',
data: {id: mailId},
success: function(data) {
var pnlMail = $('#<%= pnlMail.ClientID %>');
// display data here
pnlMail.show()
});
}
Another way is to handle click on client side and then emulate RowCommand event by doing something like this:
protected void gvItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = ""javascript:__doPostBack('" + gvItems.ClientID + "','MailDetailsCommand$" + DataBinder.Eval(e.Row.DataItem, "id") + "')";
}
}
And then on server side go like you already did, just in RowComamnd handler:
protected void gvItems_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MailDetailsCommand") {
// ...
}
}
Although I would not recommend this method - using _doPostBack manully is not considered as a best practice.
you give a template field which consist the button or a button field and then you can the give the commandname as something and then you can use the gridview commandeventargs and based on the commandname you can do whatever you want, and you can use the OnRowCommand to fire an event :D hope this will help you .....
You can even go for adding the onclick attribute to the cell in the RowDataBound Event, if there are any restrictions of not having the button field or like that

Categories