Format data in Repeater - asp.net

The result of a stored procedure will look like this.
1 Group Admin user1
1 Group Admin user2
1 Group Admin user3
1 Group Admin user4
1 Group Admin user5
2 Group Second user6
2 Group Second user7
2 Group Second user8
2 Group Second user9
2 Group Second user10
2 Group Second user11
I want to format the data as shown in picture .
The question is related with this
I think Repeater is the best control to use here. What you think ? If so, how can I format it ?
Is GridView with row merging a good idea ?
After reading the answer
// Page_Load
DataSet ds = GetAllUsers();
ViewState["UserRoles"] = ds;
rptParent.DataSource = ds;
rptParent.DataBind();
Other events
// ItemDataBound
protected void rptParent_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if ((item.ItemType == ListItemType.Item) ||
(item.ItemType == ListItemType.AlternatingItem))
{
string s = e.Item.DataItem.ToString();
string roleID = ((HiddenField)e.Item.FindControl("hidRoleId")).Value;
Repeater childRepeater = (Repeater)item.FindControl("rptChild");
string filterExp = "RoleId=" + roleID;
DataTable dtChild = ((DataSet)ViewState["UserRoles"]).Tables[0];
DataRow[] dr = dtChild.Select(filterExp);
childRepeater.DataSource = dr;
childRepeater.DataBind();
}
}
Mark up
// MarkUp
<asp:Repeater runat="server" ID="rptParent" OnItemDataBound="rptParent_ItemDataBound">
<ItemTemplate>
<table>
<tr>
<td>
<asp:HiddenField ID="hidRoleId" runat="server" Value='<%#Eval("RoleId")%>' />
<asp:Label ID="lblRoleName" runat="server" Text='<%#Eval("RoleName")%>'></asp:Label>
</td>
<td>
<asp:CheckBox ID="CheckBox4" runat="server" />
</td>
<td>
<asp:CheckBox ID="CheckBox5" runat="server" />
</td>
<td>
<asp:CheckBox ID="CheckBox6" runat="server" />
</td>
</tr>
</table>
<asp:Repeater ID="rptChild" runat="server">
<ItemTemplate>
<table>
<tr>
<td>
<asp:HiddenField ID="hidRoleId" runat="server" Value='<%#Eval("UserId")%>' />
<asp:Label ID="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "UserName") %>'></asp:Label>
</td>
<td>
<asp:CheckBox ID="CheckBox7" runat="server" />
</td>
<td>
<asp:CheckBox ID="CheckBox8" runat="server" />
</td>
<td>
<asp:CheckBox ID="CheckBox9" runat="server" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
I get the following output
But the Group name is also repeating :(. This is NOT what I want

I would use a nested repeater.
With Linq you can easily group your data and bind this to the outer repeater (and set the values for the 3 top checkboxes) and then the OnDataBound of the outer repeater can set the User list as datasource for the nested repeater.
Markup would look like:
<asp:Repeater runat="server" ID="ParentRepeater" OnItemDataBound="ParentRepeater_ItemDataBound">
<ItemTemplate>
// Markup for the three top checkboxes
<asp:Repeater runat="server" ID="ChildRepeater">
<ItemTemplate>
// Inner layout for each user with checkboxes
</ItemTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
And in the code behind:
protected void ParentRepeater_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if ((item.ItemType == ListItemType.Item) ||
(item.ItemType == ListItemType.AlternatingItem))
{
var data = item.DataItem as <YourType>;
Repeater childRepeater = (Repeater)item.FindControl("ChildRepeater");
childRepeater .DataSource = data.<InnerResults>;
childRepeater .DataBind();
}
}
If you need to use an anonymous type for your grouping have a look at the Tuple<,> class. That can help if you want to cast the item.DataItem back to a known type.

Related

Hide EmptyDataTemplate but leave header visible

I have an EmptyDataTemplate on my ASP.NET webform which allows users to add a record to the database. Depending on the permissions of the user, this EmptyDataTemplate needs to be visible and hidden if no data is found (I have this working!)
For example, my user has Read Access only. When they search a specific criteria, no results are displayed they cannot see the EmptyDataTemplate. However, if they search a criteria, and there is data, data is displayed WITHOUT the headers.
Can someone please help explain why this is happening and if there's a way around it?
The headers are HeaderText on TemplateFields.
I'm hoping it's a general trick.
Thank you in advance for your help!
Please note, it's the HeaderText in the TemplateFields I want to display- not the in the emptyDataTemplate as they'll head up the columns of data that match the search criteria.
edit: code added as requested
For hiding the EmptyDataTemplate:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Control control = null;
control = GridView1.Controls[0].Controls[0];
if (userManagement.getMIFReadWriteAccess() == "Read")
{
control.Visible = false;
Export_All.Visible = true;
}
else if (userManagement.getMIFReadWriteAccess() == "Write")
{
control.Visible = true;
Export_All.Visible = true;
}
}
in markup for the header text (i've only shown one column but the markup is the same for all of them)
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_Index" runat="server" Text='<%#Eval("id") %>'></asp:Label>
<asp:Label ID="lbl_ID" runat="server" Text="" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
EmptyDataTemplate:
<EmptyDataTemplate>
<div id="emptyData" runat="server">
<tr>
<th></th>
<th>Serial Number</th>
<th>Comments</th>
<th>Review Date</th>
<th>Approved By</th>
</tr>
<tr>
<td>
<asp:Button runat="server" ID="btInsert" Text="In" OnClick="Add" CommandName="EmptyDataTemplate" Class="Button" OnClientClick="return confirm('You are about to confirm this action. Please confirm this action by clicking OK. If you do not wish to do this, please select Cancel.');" />
<br />
<asp:Button runat="server" ID="btInsertOut" Text="Out" OnClick="AddOut" CommandName="EmptyDataTemplate" Class="Button" OnClientClick="return confirm('You are about to confirm this action. Please confirm this action by clicking OK. If you do not wish to do this, please select Cancel.');" />
</td>
<td>
<asp:TextBox runat="server" ID="tb_Serial_Number" CssClass="text"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="tb_comments" Width="100%" MaxLength="50" runat="server" placeholder="max 50 characters"/>
</td>
<td>
<asp:TextBox ID="tb_reviewDate" runat="server" DataFormatString="{0:dd/mm/yyyy}" Text='<%#Eval("review_by") %>'></asp:TextBox>
</td>
<td><asp:DropDownList ID="tb_approved_by" runat="server">
</asp:DropDownList> </td>
</tr>
</div>
</EmptyDataTemplate>
After trial and error, I found that programatically adding a header row in C# did the trick. Probably not the best way of doing it, but it worked.
Code is as follows:
#region show the emptyDataTemplate depending on user rights
Control control = null;
control = GridView1.Controls[0].Controls[0];
if (userManagement.getMIFReadWriteAccess() == "Read")
{
control.Visible = false;
GridViewRow HeaderRow = new GridViewRow(1, 0, DataControlRowType.Header, DataControlRowState.Insert);
TableCell HeaderCell2 = new TableCell();
HeaderCell2.Text = "Country";
HeaderCell2.ColumnSpan = 1;
HeaderRow.Cells.Add(HeaderCell2);
//Repeat the above for every column of data you have!
GridView1.Controls[0].Controls.AddAt(0, HeaderRow);

asp.net datalist select all checkboxes per category

I have a page where users can select different documents files in a datalist control. The documents are categorized based on categories using the on pre-render event handler. Documents are selected based on Checkbox controls (not Checkboxlist). So far so good. What I want to happen next is to put a 'Select All' checkbox beside each Category's name which should select only checkboxes under that category. Here is the datalist control:
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Vertical" OnPreRender="DataList1_PreRender" DataKeyField="docid" EnableViewState="false">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr>
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Font-Underline="True"></asp:Label>
<asp:Label runat="server" id="lbl_cb_all" visible="false">Select All <input runat="server" id="cb_selectall" type="checkbox" value='<%# Eval("catid") %>' /> </asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:Label ID="lbl_categoryname" runat="server" Text='<%# Eval("categoryname") %>' Visible="false" /> <!-- Hide this; only used in Code Behind -->
<input runat="server" id="cb_docid" type="checkbox" value='<%# Eval("docid") %>' />
<asp:Hyperlink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>' Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
and here is the OnPreRender code:
protected void DataList1_PreRender(object sender, EventArgs e)
{
string strTempLabelCategory = "";
foreach (DataListItem item in DataList1.Items)
{
Label lbl_categoryname = item.FindControl("lbl_categoryname") as Label;
if (strTempLabelCategory.ToUpper() != lbl_categoryname.Text.ToString().ToUpper())
{
strTempLabelCategory = lbl_categoryname.Text.ToString().ToUpper();
Label lblHeader = item.FindControl("lblHeader") as Label;
lblHeader.Text = strTempLabelCategory.ToUpper();
Label lbltempdiv = item.FindControl("lbl_cb_all") as Label;
lbltempdiv.Visible = true;
}
}
}
I have looked for something which can work within my code but no luck. And I am too invested in this code to now try Checkboxlist control (not sure if that would help anyway).
Any ideas? I thought I could use: http://www.dotnetcurry.com/ShowArticle.aspx?ID=77 code but not sure how I can make that work? If I can somehow make the select all checkbox tie to a tag and then look for all tag then may be the link's code would help.
Thanks!
Use HiddenFields to store CatID and DocID
Use ASP.NET CheckBoxes instead of HTML-Inputs for both
Handle the Check-All Checkbox' CheckedChanged event:
protected void CheckAllChanged(Object sender, EventArgs e)
{
CheckBox checkAll = (CheckBox)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"));
foreach (CheckBox docCheckBox in catCheckBoxes)
{
docCheckBox.Checked = checkAll.Checked;
}
}
on aspx:
<asp:CheckBox runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true" id="cb_selectall" />
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:HiddenField ID="HiddenDocID" runat="server" Value='<%# Eval("DocID") %>' />
You also need to EnableViewState=true on the DataList to maintain checkbox state and enable checking/unchecking.
Edit:
Because you have problems to get it running, here's a complete working sample page.
Here are the required controls on aspx(note f.e. <tr runat="server" id="tr_category">):
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr runat="server" id="tr_category">
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Text='<%# Eval("categoryname") %>' Font-Underline="True"></asp:Label>
<asp:Label runat="server" ID="lbl_cb_all">Select All
<asp:CheckBox runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true" id="cb_selectall" />
</asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:CheckBox runat="server" id="cb_docid" />
<asp:HyperLink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>'
Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
Ensure that the DataList is databound only if(!IsPostback), otherwise the checkbox selection will not be maintained:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) BindDataList();
}
I'm using ItemDataBound instead of PreRender which is important for the ViewState to be reloaded correctly. I've also simplified all:
protected void DataList1_ItemDataBound(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
var row = (DataRowView)e.Item.DataItem;
var view = row.DataView;
var lastRow = e.Item.ItemIndex == 0 ? null : view[e.Item.ItemIndex-1];
var tr_category = (System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("tr_category");
var sameCategory = lastRow != null && (int)row["catid"] == (int)lastRow["catid"];
tr_category.Visible = !sameCategory;
}
}
The CheckAllChanged remains unchanged.
This works as expected even if you select a single document-checkbox and select a category-checkbox afterwards which causes a postback.
I think I got this to work with slight modification of Tim's code. A few points: I had to disable ViewState for the datalist because, otherwise, the check-all trigger was not keeping boxes checked. I don't understand why. Also, there is not ispostback check in the page_load event and the datalist binds on every load. I am not that's 'optimal' or not. I have also made two sets of Asp:RadioButtons: CheckAll and CheckNone, instead of checkboxes. Anyway, here is the relevant code:
<asp:DataList ID="DataList1" runat="server" RepeatDirection="Vertical" DataKeyField="docid"
EnableViewState="false" OnItemDataBound="DataList1_ItemDataBound">
<ItemTemplate>
<table cellpadding="0" cellspacing="0" id="tbl_data">
<tr runat="server" id="tr_category">
<td>
<asp:Label ID="lblHeader" runat="server" Font-Bold="True" Text='<%# Eval("categoryname") %>'
Font-Underline="True"></asp:Label>
<asp:Label runat="server" ID="lbl_cb_all">Select: All
<asp:RadioButton runat="server" OnCheckedChanged="CheckAllChanged" AutoPostBack="true"
ID="rb_selectall" GroupName="selectallnone" />
| None
<asp:RadioButton runat="server" OnCheckedChanged="CheckAllChangedNone" AutoPostBack="true"
ID="rb_selectnone" GroupName="selectallnone" />
<asp:HiddenField ID="HiddenCatID" runat="server" Value='<%# Eval("CatID") %>' />
<asp:HiddenField ID="HiddenDocID" runat="server" Value='<%# Eval("docid") %>' />
</asp:Label>
</td>
</tr>
<tr runat="server" id="tr_data">
<td>
<asp:CheckBox runat="server" ID="cb_docid" Value='<%# Eval("docid") %>' />
<asp:HyperLink ID="hpl_docfileencr" Text='<%# Eval("docfileencr") %>' NavigateUrl='<%# "~/PDFEncr/" + DataBinder.Eval(Container.DataItem, "docfileencr") %>'
Target="_blank" runat="server" />
<br />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
protected void DataList1_ItemDataBound(Object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var row = (DataRowView)e.Item.DataItem;
var view = row.DataView;
var lastRow = e.Item.ItemIndex == 0 ? null : view[e.Item.ItemIndex - 1];
var tr_category = (System.Web.UI.HtmlControls.HtmlTableRow)e.Item.FindControl("tr_category");
var sameCategory = lastRow != null && (int)row["catid"] == (int)lastRow["catid"];
tr_category.Visible = !sameCategory;
}
}
protected void CheckAllChanged(Object sender, EventArgs e)
{
RadioButton checkAll = (RadioButton)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"))
.ToList();
foreach (CheckBox docCheckBox in catCheckBoxes)
{
// docCheckBox.Checked = checkAll.Checked;
docCheckBox.Checked = true;
}
}
protected void CheckAllChangedNone(Object sender, EventArgs e)
{
RadioButton checkAll = (RadioButton)sender;
DataListItem item = (DataListItem)checkAll.NamingContainer;
HiddenField HiddenCatID = (HiddenField)item.FindControl("HiddenCatID");
var catCheckBoxes = DataList1.Items.Cast<DataListItem>()
.Where(li => ((HiddenField)li.FindControl("HiddenCatID")).Value == HiddenCatID.Value)
.Select(li => li.FindControl("cb_docid"))
.ToList();
foreach (CheckBox docCheckBox in catCheckBoxes)
{
docCheckBox.Checked = false;
}
}
//partial code from the Order button follows; note the use of HiddenField
CheckBox cb = li.FindControl("cb_docid") as CheckBox;
if (cb != null)
{
if (cb.Checked)
{
HiddenField docid = li.FindControl("HiddenDocID") as HiddenField;
string dbcmd = #"Insert Into [order_details] (orderid,docid) Values (" + orderid + "," + docid.Value.ToString() + ")";
protected void chkAllN_CheckedChanged(object sender, EventArgs e)
{
lblSelectedRecord.InnerText = "0";
/*this Foreach Loop performing for find gridview*/
foreach (DataListItem dst in dstMulEmpSalInsert.Items)
{
GridView grd = (GridView)dst.FindControl("grdMulEmpSalInsert");
CheckBox chk_All = (CheckBox)grd.HeaderRow.FindControl("chkAllN");
if (chk_All.Checked == true)
{
/*this Foreach Loop performing for find gridview Controls*/
foreach (GridViewRow gvr in grd.Rows)
{
CheckBox chk_One = (CheckBox)gvr.FindControl("ChkSendOne");
chk_One.Checked = true;
txt_Salary.ReadOnly = false;
lblSelectedRecord.InnerText = (Convert.ToInt32(lblSelectedRecord.InnerText) + 1).ToString();
}
}
else
{
/*this Foreach Loop performing for find gridview Controls*/
foreach (GridViewRow gvr in grd.Rows)
{
CheckBox chk_One = (CheckBox)gvr.FindControl("ChkSendOne");
chk_One.Checked = false;
}
}
}
}

How to get item click event in asp.net repeater control?

I am using a repeater control to show some data on my page.
The repeater item template has an image and a label field.
I want that when i click the image , I get an event containing the id field of my data item.
How can I achieve this ?
Actually when I click the image i want to go to another page and want to show detailed information of my data item, in repeater i m just showing short information.
My repeater looks like this:
<asp:Repeater ID="itemRepeater" runat="server" OnItemCreated="itemRepeater_ItemCreated" >
<ItemTemplate>
<tr>
<td colspan="2">
<asp:Image ID="phImage" runat="server" ImageUrl='<%#"~/ImageHandler.ashx?id=" + DataBinder.Eval(Container.DataItem, "PhotoID")%>' />
</td>
<td>
<asp:Label ID="lblImageName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
I want to get PhotoID in the event when i click the image.
My photo class looks like this:
public class PhotoDC
{
public byte[] ImagebyteArray { get; set; }
public string Name { get; set; }
public int PhotoID { get; set; }
}
I have been doing winform programming just started web, maybe it is easy but i m struggling to find a solution.
I somehow managed to show hand cursor when i hover the image though.
Try this:
<asp:Repeater ID="itemRepeater" runat="server" OnItemCreated="itemRepeater_ItemCreated" >
<ItemTemplate>
<tr>
<td colspan="2">
<asp:ImageButton ID="phImage" runat="server" ImageUrl='<%#"~/ImageHandler.ashx?id=" + DataBinder.Eval(Container.DataItem, "PhotoID")%>' OnCommand="Image_Click" CommandName="ImageClick" CommandArgument='<%# Eval("PhotoID") %>' />
</td>
<td>
<asp:Label ID="lblImageName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
protected void Image_Click(object sender, CommandEventArgs e)
{
if (e.CommandName == "ImageClick"){
//e.CommandArgument --> photoid value
//Do something
}
}
You can use ItemCommand of repeater control
like this -
protected void itemRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (e.CommandName == "img_Click") // check command is cmd_delete
{
// get you required value
int CustomerID = Convert.ToInt32(e.CommandArgument);
//Write some code for what you need
}
}
}
Personally I think the simplest way to handle something like this is to simply use the ItemTemplate to generate a regular html link, rather than do any thing in the code-behind. Something like this:
<asp:Repeater ID="itemRepeater" runat="server" OnItemCreated="itemRepeater_ItemCreated" >
<ItemTemplate>
<tr>
<td colspan="2">
<a href="/Details.aspx?id=<%=DataBinder.Eval(Container.DataItem, "PhotoID")%>">
<asp:Image ID="phImage" runat="server" ImageUrl='<%#"~/ImageHandler.ashx?id=" + DataBinder.Eval(Container.DataItem, "PhotoID")%>' />
</a>
</td>
<td>
<asp:Label ID="lblImageName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
</td>
</tr>
</ItemTemplate>
I know this isn't strictly the question you asked, but IMHO it's the best approach to accomplish the task.

GridView isn't reflecting AJAX changes

I'm using AJAX right now to update my GridView when I search for a string of text in the gridview, or when I select from a dropdownlist what I want to order the Gridview by. This was working previously, but I had really messy code. So I've cleaned it up a little bit, added some parameters and such. Unfortunately, now, when the selectedindex of the dropdownlist is changed or when someone tries to search for a field, nothing happens - the page just refreshes. I'm also getting an exception saying "The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name".
If you need to see any more code then please let me know!
public vieworders()
{
this.PreInit += new EventHandler(vieworders_PreInit);
}
void vieworders_PreInit(object sender, EventArgs e)
{
orderByString = orderByList.SelectedItem.Value;
fieldString = searchTextBox.Text;
updateDatabase(fieldString, orderByString);
}
protected void updateDatabase(string _searchString, string _orderByString)
{
string updateCommand = "SELECT fName,lName,zip,email,cwaSource,price,length FROM SecureOrders WHERE fName LIKE #searchString OR lName LIKE #searchString OR zip LIKE #searchString OR email LIKE #searchString OR cwaSource LIKE #searchString OR length LIKE #searchString OR price LIKE #searchString ORDER BY #orderByString";
Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Cabot3");
ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["secureodb"];
// Create an SqlConnection to the database.
using (SqlConnection connection = new SqlConnection(connectionString.ToString()))
using (SqlCommand _fillDatabase = new SqlCommand(updateCommand, connection))
{
connection.Open();
_fillDatabase.Parameters.Add("#searchString", SqlDbType.VarChar, 50).Value = _searchString;
_fillDatabase.Parameters.Add("#orderByString", SqlDbType.VarChar, 50).Value = _orderByString;
_fillDatabase.ExecuteNonQuery();
dataAdapter = new SqlDataAdapter("SELECT * FROM SecureOrders", connection);
// create the DataSet
dataSet = new DataSet();
// fill the DataSet using our DataAdapter
dataAdapter.Fill(dataSet, "SecureOrders");
DataView source = new DataView(dataSet.Tables[0]);
DefaultGrid.DataSource = source;
DefaultGrid.DataBind();
connection.Close();
}
}
Form
<form id="form1" runat="server">
<asp:ScriptManager ID = "ScriptManager" runat="server" />
<div>
<asp:Label runat="server" id = "orderByLabel" Text = "Order By: " />
<asp:DropDownList runat="server" ID="orderByList" AutoPostBack="true">
<asp:ListItem Value="fName" Selected="True">First Name</asp:ListItem>
<asp:ListItem Value="lName">Last Name</asp:ListItem>
<asp:ListItem Value="state">State</asp:ListItem>
<asp:ListItem Value="zip">Zip Code</asp:ListItem>
<asp:ListItem Value="cwaSource">Source</asp:ListItem>
<asp:ListItem Value="cwaJoined">Date Joined</asp:ListItem>
</asp:DropDownList>
</div>
<div>
<asp:Label runat="server" ID="searchLabel" Text="Search For: " />
<asp:TextBox ID="searchTextBox" runat="server" Columns="30" />
<asp:Button ID="searchButton" runat="server" Text="Search" />
</div>
<div>
<asp:UpdatePanel ID = "up" runat="server">
<ContentTemplate>
<div style= "overflow:auto; height:50%; width:100%">
<asp:GridView ID="DefaultGrid" runat = "server" DataKeyNames = "IdentityColumn"
onselectedindexchanged = "DefaultGrid_SelectedIndexChanged"
autogenerateselectbutton = "true">
<SelectedRowStyle BackColor="Azure"
forecolor="Black"
font-bold="true" />
<Columns>
<asp:TemplateField HeaderText="Processed">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxProcess" AutoPostBack = "true" Checked ='<%#Eval("processed") %>' OnCheckedChanged="CheckBoxProcess_CheckedChanged" runat="server" Enabled="true" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
<div style= "overflow:auto; height:50%; width:100%" />
<table border="1">
<tr>
<td>Name: </td>
<td><%=name %></td>
</tr>
<tr>
<td>Zip: </td>
<td><%=zip %></td>
</tr>
<tr>
<td>Email: </td>
<td><%=email %></td>
</tr>
<tr>
<td>Length: </td>
<td><%=length %></td>
</tr>
<tr>
<td>Price: </td>
<td><%=price %></td>
</tr>
<tr>
<td>Source: </td>
<td><%=source %></td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
I have never used the UpdatePanel since my company uses Telerik, but from the examples I see during my research I remember seeing a trigger component.
From my understanding, if the control is w/i the UpdatePanel itself, then you do not have to specify the trigger, since it is assumed.
For your scenario, the trigger (dropdownlist) is outside of the UpdatePanel. You may need to include this in your aspx:
<asp:UpdatePanel ID = "up" runat="server">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="orderByList" >
</Triggers>
<ContentTemplate>
...
Try the following:
In HTML move the update panel direct after the scriptmanager line.
Move the code lines in vieworders_PreInit to vieworders_PageLoad with !IsPostPack clause.

create a filter row with textboxes on each column in asp.net gridview

I have a asp.net gridview, which i am binding at runtime with a custom List object. I want to add a filter row below the header row on each column and on click of filter button grid data should get filtered based on values written in the filter textboxes. requirement seems weird but this is what client wants. please help with some clue.
aspx code :
<asp:TemplateField>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="150px" />
<HeaderTemplate>
<table>
<tr>
<td align="center">
<asp:ImageButton runat="server" ID="imgFilter1" ImageUrl="../Images/filter.png" Style="height: 20px;
width: 20px;" OnClick="imgFilter1_click" />
</td>
<td align="center">
<asp:TextBox runat="server" ID="gridTextboxFilter1" AutoPostBack="true" onTextChanged="gridTextboxFilter1_text_changed">
</asp:DropDownList>
</td>
</tr>
<tr>
<td align="center" colspan="2">
//your column header
</td>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" Text='<%# Eval("your_dataFeild") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
cs code :
private void BindGrid(string strFilter)
{
try
{
// Simple created a table to bind with Grid view and
// populated it with data.
DataTable dt = new DataTable("sample");
dt.Columns.Add("ID");
dt.Columns.Add("Name");
DataRow dr ;
for(int counter=1;counter<11;counter++)
{
dr = dt.NewRow();
dr["ID"]=counter.ToString();
dr["Name"]= "Cat" + counter.ToString();
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
if(strFilter != "")
dv.RowFilter="Name like '%" + strFilter + "%'";
if (CategoryFilter == "")
gvCategory.DataSource = dv;
else
gvCategory.DataSource = dv;
gvCategory.DataBind();
}
catch (Exception ex)
{
}
finally
{
}
}
protected void gridTextboxFilter1_text_changed(object sender, EventArgs e)
{
string text = ((TextBox)sender).Text;
BindGrid(text);
}
Add a textbox and button on the header template.
Write a query on button press and get the value.
The query something like select * from tbl where col like '%val%'
Bind the value to gridView.
I think this will solves for you

Resources