I am looking to populate a (sorted) GridView (called SearchResultsGid) without the use of a data source control. I did some research and I am guessing I may need to use a data set and datable to successfully bind the the grid, but I am not entirely sure how to do it. I'm more used to using a data source control....
The grid view uses Eval statements, which I would like to keep if possible because it allows for the fields to be hyperlinks to other pages. Although, if there is another way, I would be willing to try it...
The point of the SearchResultsGrid is that, when the user types in something in a text field then hits the "search" button, a grid pops up with all relevant results from the database. There is a repeater which displays all database items that the user has added for viewing, but it is not relevant to me at the moment (it works just fine anyway).
Any help would be appreciated! :)
Here is the code:
<table cellpadding="4" cellspacing="0" class="inputForm" width="100%">
<tr><td width="100%"><p align="justify">Select the products that should have this option.</p></td></tr>
<tr>
<td valign="top">
<asp:Label ID="errorLbl" ForeColor="Red" Font-Bold="true" runat="server" Text=""></asp:Label>
<asp:UpdatePanel ID="MainContentAjax" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div class="section">
<div class="header"><h2><asp:Localize ID="FindProductsCaption" runat="server" Text="Find Products" /></h2></div>
<asp:Panel ID="SearchFormPanel" runat="server" CssClass="content" DefaultButton="SearchButton">
<table class="inputForm">
<tr>
<th class="rowHeader"><cb:ToolTipLabel ID="SearchNameLabel" runat="server" Text="Product Name:" ToolTip="Enter all or part of a product name. Wildcard characters * and ? are accepted." /></th>
<td><asp:TextBox ID="SearchName" runat="server" Text="" /></td>
<th class="rowHeader"><cb:ToolTipLabel ID="ShowImagesLabel" runat="server" Text="Show Thumbnails:" ToolTip="When checked, product images will be displayed in the search results." /></th>
<td><asp:CheckBox ID="ShowImages" runat="server" /></td>
<td><asp:LinkButton ID="SearchButton" runat="server" Text="Search" SkinID="Button" OnClick="SearchButton_Click" /></td>
</tr>
</table>
<cb:SortedGridView ID="SearchResultsGrid" runat="server" AutoGenerateColumns="False" DataKeyNames="ProductId" GridLines="None" SkinID="PagedList" Width="100%" AllowPaging="true" Visible="false" DefaultSortExpression="Name" EnableSortingAndPagingCallbacks="True" PageIndex="0" AllowSorting="True">
<Columns>
<asp:TemplateField HeaderText="Thumbnail">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:HyperLink ID="NodeImageLink" runat="server" NavigateUrl='<%# UrlGenerator.GetBrowseUrl((int)Eval("ProductId"), CatalogNodeType.Product, (string)Eval("Name")) %>'> <asp:Image ID="NodeImage" runat="server" ImageUrl='<%# Eval("ThumbnailUrl") %>' Visible='<%# !string.IsNullOrEmpty((string)Eval("ThumbnailUrl")) %>' AlternateText='<%# Eval("Name") %>' /> </asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SKU" SortExpression="Sku">
<HeaderStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:HyperLink ID="ProductSku" runat="server" Text='<%#Eval("Sku")%>' SkinID="FieldHeader" /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item" SortExpression="Name" >
<HeaderStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:HyperLink ID="ProductName" runat="server" Text='<%#Eval("Name")%>' SkinID="FieldHeader" /><br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned">
<ItemStyle Width="50px" HorizontalAlign="Center" />
<ItemTemplate>
<asp:ImageButton ID="AttachButton" runat="server" CommandArgument='<%#Container.DataItemIndex%>' AlternateText="Add" ToolTip="Add" SkinID="AddIcon" OnClientClick="this.visible=false" OnClick="AttachButton_Click" Visible='<%#!IsProductLinked(((Product)Container.DataItem).ProductId)%>' />
<asp:ImageButton ID="RemoveButton" runat="server" CommandArgument='<%#Container.DataItemIndex%>' AlternateText="Remove" ToolTip="Remove" SkinID="DeleteIcon" OnClientClick="return confirm('Are you sure you want to remove this item from this option?')" OnClick="RemoveButton_Click" Visible='<%#IsProductLinked(((Product)Container.DataItem).ProductId)%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
There are no products that match the search text.
</EmptyDataTemplate>
</cb:SortedGridView>
</asp:Panel>
</div>
<div class="section">
<div class="header"><h2>Assigned Products</h2></div>
<div class="content">
<asp:Repeater ID="RelatedProductGrid" runat="server" SkinID="PagedList" OnItemCommand="RelatedProductGrid_RowDeleting">
<HeaderTemplate>
<table width="100%" class="pagedList" cellpadding="0" cellspacing="0">
</HeaderTemplate>
<ItemTemplate>
<tr class="oddRow">
<td>
<asp:Label ID="ProdID" runat="server" Text='<%#Eval("ProductId") %>' Visible="false" />
<asp:HyperLink ID="ProductName2" runat="server" Text='<%#Eval("Name")%>' NavigateUrl='<%#Eval("ProductId", "/Admin/products/EditProduct.aspx?ProductId={0}")%>' />
</td>
<td><asp:ImageButton ID="RemoveButton2" runat="server" SkinID="DeleteIcon" CommandName="Delete" CommandArgument='<%#Eval("ProductId") %>' AlternateText="Remove" ToolTip="Remove" OnClientClick="return confirm('Are you sure you want to remove this item from this option?')" /></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr class="evenRow">
<%-- <td>
<asp:Label ID="ProdID2" runat="server" Text='<%#Eval("ProductId") %>' Visible="false" />
<asp:HyperLink ID="ProductSku" runat="server" Text='<%#Eval("Sku")%>' NavigateUrl='<%#Eval("ProductId", "/Admin/products/EditProduct.aspx?ProductId={0}")%>' />
</td>--%>
<td>
<asp:Label ID="ProdID" runat="server" Text='<%#Eval("ProductId") %>' Visible="false" />
<asp:HyperLink ID="ProductName2" runat="server" Text='<%#Eval("Name")%>' NavigateUrl='<%#Eval("ProductId", "/Admin/products/EditProduct.aspx?ProductId={0}")%>' />
</td>
<td><asp:ImageButton ID="RemoveButton2" runat="server" SkinID="DeleteIcon" CommandName="Delete" CommandArgument='<%#Eval("ProductId") %>' AlternateText="Remove" ToolTip="Remove" /></td>
</tr>
</AlternatingItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</div>
<asp:Button ID="FinishButton" runat="server" Text="Finish" OnClick="FinishButton_Click" /><br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
I started work on the function to populate the SearchResultsGrid, and the SQL command is how I want to be in terms of getting the correct information on the button click. I plan to call this function inside the button click.
protected void PopulateSearchGrid()
{
try
{
System.Data.SqlClient.SqlDataReader dr = null;
DataSet ds = new DataSet();
DataTable resultsTbl = ds.Tables.Add("resultsTbl");
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT OptionID, ac_Products.Name, Sku FROM ac_Options, ac_Products WHERE OptionID = #OptionID AND ac_Products.Name = #Name", cn))
{
///and this is where I'm getting confused on what to do :(
}
}
}
catch { }
}
You may use a DataTable object, populating it with a SQL query, and assign it to the datasource of the grid.
Use your DataAdapter to fill your DataTable with your SQL query (mind to match column names with those on your GridView)
DataTable dt = new DataTable();
//use your DataAdapter to fill the data table
sda.Fill(dt);
SearchResultsGrid.DataSource = dt;
SearchResultsGrid.DataBind();
Your query is using parameters, so you might want to use a SqlCommand instead of specifying the SQL directly on your SqlDataAdapter.
SqlCommand cmd = new SqlCommand("Your Query",cn);
cmd.Parameters.Add("Your first parameter", your param value);
cmd.Parameters.Add("Your second parameter", your param value);
... new SqlDataAdapter(cmd)...
Related
Soo I'm trying to filter my gridview with textboxes in the header. I created a textchanged method for every textbox. Now I want to filter the gridview and bind the filtered data. For some reason the datasource is null once it hits the textchanged method. See my code below:
<asp:GridView ID="GridView_Imported" runat="server" CssClass="GridView-Upload" Width="100%" OnRowDataBound="GridView_Imported_RowDataBound" HorizontalAlign="Center" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" CssClass="checkAll" onclick="checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkCtrl" runat="server" CssClass="chkCtrl" onclick="Check_Click(this)" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField AccessibleHeaderText="filter">
<HeaderTemplate>
<asp:Label ID="lbArticleName" runat="server" Text="Article-Name:" CssClass="Article-Name-Label"></asp:Label>
<br/>
<asp:TextBox ID="tbFilterArticleName" runat="server" placeholder="Filter..." OnTextChanged="tbFilterArticleName_TextChanged" AutoPostBack="True"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="ArticleNameText" runat="server" Text='<%# Eval("Article-Name") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lbArticle" runat="server" Text="Article:" CssClass="Article-Label"></asp:Label>
<br/>
<asp:TextBox ID="tbFilterArticle" runat="server" placeholder="Filter..." OnTextChanged="tbFilterArticle_TextChanged" AutoPostBack="True"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbArticleText" runat="server" Text='<%# Eval("Article") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lbWarehouse" runat="server" Text="Warehouse:" CssClass="Warehouse-Label"></asp:Label>
<br/>
<asp:TextBox ID="tbFilterWarehouse" runat="server" placeholder="Filter..." OnTextChanged="tbFilterWarehouse_TextChanged" AutoPostBack="True"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbWarehouseText" runat="server" Text='<%# Eval("Warehouse") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="lbLocation" runat="server" Text="Location:" CssClass="Location-Label"></asp:Label>
<br/>
<asp:TextBox ID="tbFilterLocation" runat="server" placeholder="Filter..." OnTextChanged="tbFilterLocation_TextChanged" AutoPostBack="True"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbLocationText" runat="server" Text='<%# Eval("Location") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" />
</asp:GridView>
protected void tbFilterArticleName_TextChanged(object sender, EventArgs e)
{
var tb = (TextBox) sender as TextBox;
GridView_Imported.DataSource = (Session["dataSource"] as DataTable).DefaultView.RowFilter = string.Format("Article-Name LIKE '%{0}%'", tb.Text.Trim());
GridView_Imported.DataBind();
}
What I'm missing?
There are two errors in your code.
First put brackets for column name Article-Name as [Article-Name].
Second the way you assigning datasource to gridview. See the correct way below.
var dt = (Session["dataSource"] as DataTable);
dt.DefaultView.RowFilter = string.Format("[Article-Name] LIKE '%{0}%'", tb.Text.Trim());
GridView_Imported.DataSource = dt;
GridView_Imported.DataBind();
Use http://www.datatables.net/
It provides data filtering, sorting, paging etc.
Just place a html table header above your gridview with some id
<HeaderTemplate>
<table id="tblData" border="0" cellpadding="5" cellspacing="1" width="100%">
<thead>
<th align="center" width="3%">S.No.
</th>
<th align="center" width="10%">RFQ ID
</th>
</thead>
</HeaderTemplate>
Add add jquery script
$(document).ready(function () {
$('#tblData').DataTable();
});
First, in RowDataBound event of your gridview(to find your textbox):
System.Web.UI.WebControls.TextBox tbFilterArticle;
protected void GridView_Imported_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (GridView_Imported.HeaderRow != null)
{
tbFilterArticle = (System.Web.UI.WebControls.TextBox)GridView_Imported.HeaderRow.FindControl("tbSearchUser");
}
}
After that, to use it's value(anywhere you want, i used it into a button click event):
string article = tbFilterArticle.Text;
I have a form with some text boxes and a button, which when clicked (button), a modalpopup extender will open with values display in grid-view (values from database),
If the user select any row, the name of the selected person must display in the text box of the parent form as shown below;
I have written this code,
C# Code:
//GridView inside the Modal popup
protected void grdPersonDetails_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = grdPersonDetails.SelectedRow;
Session["testSession"] = row.Cells[0].Text;
ViewState["testViewState"] = row.Cells[0].Text;
ChargeFilterModalDialogExtender.Hide();
txtPersonName.Text = (string) ViewState["sometest"];
txtPersonName.Text = (string) Session["sometest"];
}
ASP Code:
<asp:Label ID="Label1" runat="Server" Text="Person Name:"></asp:Label>
<asp:TextBox runat="Server" ID="txtPersonName" />
<asp:Button runat="server" ID="btnSelectPerson" Text="Select Person" />
<ajax:ModalPopupExtender ID="ChargeFilterModalDialogExtender" runat="server" TargetControlID="btnSelectPerson" CancelControlID="BtnCloseChargeFilterControl" Drag="false" PopupControlID="Dialog_ChargeFilter" Enabled="True" BackgroundCssClass="modalBackground" />
<asp:Button ID="BtnShowDialog" Style="display: none" runat="server" Width="120" Text="Filter Charges" ToolTip="show Chargefilter-Dialog" />
<asp:Panel ID="Dialog_ChargeFilter" CssClass="modalPopup" runat="server">
<asp:Panel ID="DialogHeaderFrame" CssClass="DialogHeaderFrame" runat="server">
<asp:Panel ID="DialogHeader" runat="server" CssClass="DialogHeader" ScrollBars="Auto">
<asp:Label ID="LblPopupHeader" runat="server" Text="Charge-Filter" />
</asp:Panel>
</asp:Panel>
<asp:UpdatePanel ID="UpdGrdCharge" runat="server" UpdateMode="conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:Button ClientIDMode="Static" ID="BtnCloseChargeFilterControl" Text="close filter" ToolTip="close filter-dialog" CausesValidation="false" Width="150px" runat="server" OnClick="BtnCloseChargeFilterControl_Click" /><br />
<table border="1">
<tr>
<td dir="rtl">
<asp:GridView ID="grdPersonDetails" runat="server" AutoGenerateColumns="False" DataKeyNames="PersonName,PersonEmail" DataSourceID="TempSqlDataSource" OnSelectedIndexChanged="grdPersonDetails_SelectedIndexChanged">
<Columns>
<asp:BoundField DataField="PersonName" HeaderText="Person Name" ReadOnly="True" SortExpression="PersonName" />
<asp:BoundField DataField="PersonEmail" HeaderText="Person Email" ReadOnly="True" SortExpression="PersonEmail" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CommandName="Select" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="TempSqlDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="select * from person.persons"></asp:SqlDataSource>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
The issue is that when I am selecting a person in the grid-view (inside the modal popup), the selected person name not appear in the related text box in the parent form. (when debugging it, it shows that the value of person name set in the text box)
Hi Abdul here is a complete demo - tested by me - working 100% successfully.
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="ModalPopupExtenderAJAXToolkitWebApp._Default" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<style type="text/css">
.searchButton
{
left: 319px;
position: absolute;
top: 145px;
width: 27px;
}
</style>
<link href="Styles/jquery.tooltip.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
//Hiding Table Available inside div #dvDetails
// $('#dvDetails').hide();
/* Binding click event to each imagebutton inside GridView1
* which is taking value from current row and assigning
* to controls inside table
*/
$("#<%=GridView1.ClientID %> input[name*='imgbtn']").each(function (index) {
$("#<%=GridView1.ClientID %> input[name*='imgbtn']").bind('click', function (e) {
var id = $(this).closest('tr').find("span[id*='lblUserId']").text();
var username = $(this).closest('tr').find("input[name*='txtUserName']").val();
var firstname = $(this).closest('tr').find("input[name*='txtFirstName']").val();
var lastname = $(this).closest('tr').find("input[name*='txtLastName']").val();
var city = $(this).closest('tr').find("input[name*='txtCity']").val();
var designation = $(this).closest('tr').find("input[name*='txtDesignation']").val();
$('#<%=lblID.ClientID %>').text(id);
$('#<%=lblusername.ClientID %>').text(username);
$('#<%=txtfname.ClientID %>').val(firstname);
$('#<%=txtlname.ClientID %>').val(lastname);
$('#<%=txtCity.ClientID %>').val(city);
$('#<%=txtDesg.ClientID %>').val(designation);
});
});
/* Binding click event to each selected radiobutton inside GridView1
* which is taking value from current row and assigning
* to controls inside table
*/
$('input[value=Remove]').click(function () {
$('#dvDetails').show();
var id = $(this).closest('tr').find("span[id*='lblUserId']").text();
var username = $(this).closest('tr').find("input[name*='txtUserName']").val();
var firstname = $(this).closest('tr').find("input[name*='txtFirstName']").val();
var lastname = $(this).closest('tr').find("input[name*='txtLastName']").val();
var city = $(this).closest('tr').find("input[name*='txtCity']").val();
var designation = $(this).closest('tr').find("input[name*='txtDesignation']").val();
$('#<%=lblID.ClientID %>').text(id);
$('#<%=lblusername.ClientID %>').text(username);
$('#<%=txtfname.ClientID %>').val(firstname);
$('#<%=txtlname.ClientID %>').val(lastname);
$('#<%=txtCity.ClientID %>').val(city);
$('#<%=txtDesg.ClientID %>').val(designation);
});
var $fieldRevItems = $("#dvDetails");
$('#<%=btnClose2.ClientID %>').click(function (e) {
$('#<%=txtSearch.ClientID %>').val('');
// $fieldRevItems.hide('slow');
$fieldRevItems.slideUp(600);
e.preventDefault();
});
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to ASP.NET!
</h2>
<asp:ToolkitScriptManager ID="ScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div id="dvMain" style="height: 341px; width: 928px">
<div id="dvFirst">
Search user Details : <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
<asp:ImageButton ID="imgSearch" CssClass="searchButton" title="Search data for this id"
ImageUrl="~/search2.jpg" runat="server" OnClick="imgSearch_Click" />
<asp:Button ID="btnShowPopup2" runat="server" Style="display: none" />
<br />
<br />
<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="btnShowPopup2"
PopupControlID="pnlpopup2" CancelControlID="btnClose" BackgroundCssClass="modalBackground">
</asp:ModalPopupExtender>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="pnlpopup2" runat="server" BackColor="Green" Height="269px" Width="600px"
Style="display: none; top: 191px;width: 780px;">
<asp:GridView runat="server" ID="GridView1" DataKeyNames="UserId"
AutoGenerateColumns="false">
<rowstyle backcolor="#EFF3FB" />
<footerstyle backcolor="#507CD1" font-bold="True" forecolor="White" />
<pagerstyle backcolor="#2461BF" forecolor="White" horizontalalign="Center" />
<headerstyle backcolor="#507CD1" font-bold="True" forecolor="White" />
<alternatingrowstyle backcolor="White" />
<columns>
<asp:TemplateField HeaderText="UserId">
<ItemTemplate>
<asp:Label ID="lblUserId" style="width:100px;" runat="server" Text='<%# Eval("UserId") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblUserId" style="width:100px;" runat="server" Text='<%# Eval("UserId") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:TextBox ID="txtUserName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("UserName")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUserName" CssClass="css2" runat="server"
Text='<%# Eval("UserName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:TextBox ID="txtFirstName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("FirstName")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:TextBox ID="txtLastName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("LastName")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("LastName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<ItemTemplate>
<asp:TextBox ID="txtCity" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("City")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCity" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("City")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:TextBox ID="txtDesignation" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("Designation")%>'></asp:TextBox>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDesignation" style="width:100px;" CssClass="css2" runat="server"
Text='<%# Eval("Designation")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Close">
<ItemTemplate>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:RadioButton ID="rbSelectUserId" runat="server" Checked="false" value="Remove"
AutoPostBack="true" CausesValidation="false"
/>
<asp:ImageButton ID="imgbtn" ImageUrl="~/Edit.jpg" runat="server" Width="25" Height="25"/>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
<asp:Button ID="btnClose" runat="server" Text="Cancel" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
</div>
<div id="dvDetails">
<table id="tblDetails" width="30%" style="border: Solid 3px #D55500; height: 100%"
cellpadding="0" cellspacing="0">
<tr style="background-color: #D55500">
<td colspan="2" style="height: 10%; color: White; font-weight: bold; font-size: larger"
align="center">
User Details
</td>
</tr>
<tr>
<td align="right">
UserId:
</td>
<td>
<asp:Label ID="lblID" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
UserName:
</td>
<td>
<asp:Label ID="lblusername" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
FirstName:
</td>
<td>
<asp:TextBox ID="txtfname" runat="server" />
</td>
</tr>
<tr>
<td align="right">
LastName:
</td>
<td>
<asp:TextBox ID="txtlname" runat="server" />
</td>
</tr>
<tr>
<td align="right">
City:
</td>
<td>
<asp:TextBox ID="txtCity" runat="server" />
</td>
</tr>
<tr>
<td align="right" style="width: 100%">
Designation:
</td>
<td>
<asp:TextBox ID="txtDesg" runat="server" />
</td>
</tr>
<tr>
<td align="center" style="width: 100%">
<asp:Button ID="btnClose2" runat="server" Text="Close" />
</td>
</tr>
</table>
</div>
</div>
</asp:Content>
//====================================================================================
and here is your code behind file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Configuration;
namespace ModalPopupExtenderAJAXToolkitWebApp
{
public partial class _Default : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conString"].ToString());
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
protected void BindGridData()
{
con.Open();
using (SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
UpdatePanel1.Update();
}
}
protected DataTable SearchDetails(string id)
{
DataTable dt = new DataTable();
con.Open();
using (SqlCommand cmd = new SqlCommand("Select * from Employee_Details where UserId=#UserId", con))
{
cmd.Parameters.Add(new SqlParameter("#UserId",Convert.ToInt32(id)));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
return dt;
}
protected void imgSearch_Click(object sender, EventArgs e)
{
string id = txtSearch.Text;
if (id != null)
{
DataTable dt = new DataTable();
dt = SearchDetails(id);
GridView1.DataSource = dt;
GridView1.DataBind();
UpdatePanel1.Update();
this.ModalPopupExtender2.Show();
}
}
}
}
I have a datalist filled with items from database and each item has an image button onclick of which I want to show a modalpopup containing the Description of the particular Item. Below is what I have dine so far but fail:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%">
<ItemTemplate>
<table width="228px">
<tr>
<td width="20px" > </td>
<td width="160px" align="center">
<asp:Label ID="pID" runat="server" Visible="false" Text='<%# Eval("id") %>'></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("ProductName") %>' Font-Size="8pt" ForeColor="#336699" Width="100%" />
</td>
<td align="right">
<asp:ImageButton ID="SpecificBtn" ImageUrl="images/SmallCallout.png" OnClick="SpecificBtn_Click" CommandArgument='<%# Eval("Id") %>' runat="server" />
<ajaxToolkit:ModalPopupExtender ID="mdl" runat="server" PopupControlID="pnl" TargetControlID="SpecificBtn" Enabled="True" CancelControlID="btn" DropShadow="true" Drag="True" ></ajaxToolkit:ModalPopupExtender>
</td>
</tr>
</table>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "GetImage.aspx?id=" + Eval("id") %>' /><br />
<table align="center" style="position:relative; left:2px;" cellspacing="0" cellpadding = "0" width="228px">
<tr>
<td style="background-color:Black;" colspan=2>
<div >
<asp:Image ID="Image2" ImageUrl="/images/cart.png" runat="server" />
<asp:Button CommandName="AddToCart" CssClass="anchor" OnClick="addProduct" CausesValidation="false" CommandArgument='<%# Eval("Id") %>' ID="addToHire" runat="server" Text=" Add To Cart " BackColor="Black" BorderColor="Black" BorderStyle="None" ForeColor="#F8CD20" Height="24" Font-Bold="true" Font-Size="10" />
</div>
</td>
</tr>
</table>
<br /><br />
</ItemTemplate>
<ItemStyle CssClass="dataListItemStyle" HorizontalAlign="Center" VerticalAlign="Top" />
</asp:DataList>
<asp:Panel ID="pnl" runat="server" visible="false" Width="300px" Height="300px" BackColor="red">
<asp:Label ID="Label2" runat="server" Text="Specification"></asp:Label>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Specification") %>'></asp:Label>
<asp:Button ID="btn" runat="server" Text="cancel" />
</asp:Panel>
Code behind:
protected void SpecificBtn_Click(object sender, EventArgs e)
{
DataListItem dli = (DataListItem)((ImageButton)sender).Parent;
ModalPopupExtender ModalPopupExtender2 = (ModalPopupExtender)dli.FindControl("mdl");
pnl.Visible = true;
ModalPopupExtender2.Show();
}
Can somebody tell me how to acheive this and where I went wrong. Thanks.
use jquery..
function onimagebuttonclick()
{
$find('BehaviorIDofmodelpopupextender').show();
}
i hope this solves your problem..
I've a got ListBox called lbxUpcommingEvents. When the index is changed the event handler is fired to check for duplicate records. If duplicates are not found, a panel called pnlAction inside a formview is turned on by the way of display style. If dups are found another panel pnlActionCancel is turned on and the oter is tuned off. Basically a toogle effect.
I've tried the visible property, viewstate property, but it does not work and I can't figure it out so once again, I seek wizdom from the collective. Here is my code.
protected void lbxUpcommingEvents_OnSelectedIndexChanged(object sender, EventArgs e)
{
pnlEventsSignUp.Visible = true;
string _selectedItemValue = lbxUpcommingEvents.SelectedValue.ToString();
int _eventid = Convert.ToInt32(_selectedItemValue);
Guid _memberId = Guid.Empty;
_memberId = new Guid(Session["myId"].ToString());
// Check for existing signup
EventsMemberSignup _createSingup = new EventsMemberSignup();
dsEventsSingupTableAdapters.MemberEventsTableAdapter da = new dsEventsSingupTableAdapters.MemberEventsTableAdapter();
dsEventsSingup.MemberEventsDataTable dt = da.GetDataForDupCheck(_memberId, _eventid);
if (dt.Rows.Count == 1)
{
Panel pnlAction = (Panel)(fvEventSignUp.FindControl("pnlAction"));
//pnlAction.Visible = false;
pnlAction.Style.Add("display","none");
Panel pnlActionCancel = (Panel)(fvEventSignUp.FindControl("pnlActionCancel"));
//pnlActionCancel.Visible = true;
pnlActionCancel.Style.Remove("display");
}
else
{
Panel pnlActionCancel = (Panel)(fvEventSignUp.FindControl("pnlActionCancel"));
//pnlActionCancel.Visible = false;
pnlActionCancel.Style.Add("display", "none");
Panel pnlAction = (Panel)(fvEventSignUp.FindControl("pnlAction"));
//pnlAction.Visible = true;
pnlAction.Style.Remove("display");
}
}
<div id="columnleft">
<a name="content_start" id="content_start"></a>
<div class="leftblock">
<h2>Events Signup</h2>
<p>
</p>
<h3> Upcomming Events</h3>
<p>
<asp:ListBox ID="lbxUpcommingEvents" runat="server" DataSourceID="odsUpcommingEvents"
Rows="6" DataTextField="Title" DataValueField="id" AutoPostBack="true"
Width="206px" OnSelectedIndexChanged="lbxUpcommingEvents_OnSelectedIndexChanged" />
</p>
<h3> Members Attending</h3>
<p>
<asp:DataGrid ID="lboxSignedUpMembers" runat="server" DataSourceID="odsSignedUpMembers"
AutoPostBack="true" AutoGenerateColumns="false" RowStyle-CssClass="gridview" AlternatingRowStyle-CssClass="altbgcolor"
Width="206px" onselectedindexchanged="lboxSignedUpMembers_SelectedIndexChanged" CssClass="gridview"
GridLines="None" BorderStyle="Solid" BorderWidth="1" BorderColor="Black" >
<AlternatingItemStyle BackColor="White" />
<Columns>
<asp:BoundColumn DataField="Name" />
<asp:BoundColumn DataField="Title" />
<asp:TemplateColumn >
<ItemTemplate>
<asp:Label runat="server" ID="lblDate" Text='<%# Eval("StartTime", "{0:d}") %>' />
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
</p>
</div>
</div>
</td>
<td align="left" >
<!--Start of right column-->
<div id="columnright">
<div class="rightblock">
<asp:Panel ID="pnlEventsSignUpTitle" runat="server" CssClass="actionbuttons">
<h2>Select an Event to Signup</h2>
</asp:Panel>
<asp:Label runat="server" ID="lblNote" ForeColor="#cc0000" Font-Bold="true" />
</div>
<div class="rightblock">
<asp:Panel runat="server" ID="pnlEventsSignUp" visible="false">
<div class="dashedline" ></div>
<asp:FormView ID="fvEventSignUp" runat="server" DataSourceID="ObjectDataSource1"
DataKeyNames="id" Width="100%" >
<ItemTemplate>
<h2>
<asp:HiddenField runat="server" ID="hfEventID" Value='<%# Eval("id") %>' />
<asp:Label Text='<%# Eval("title") %>' runat="server" ID="titleLabel" />
</h2>
<div class="itemdetails">
<br />
location:
<h3>
<asp:Label ID="locationLabel" runat="server" Text='<%# ShowLocationLink(Eval("locationname"),Eval("location")) %>' />
</h3>
<p>
<asp:Label Text='<%# Eval("starttime","{0:D}") %>' runat="server" ID="itemdateLabel" CssClass="GeneralText" />
<asp:Label Text='<%# ShowDuration(Eval("starttime"),Eval("endtime")) %>' runat="server" ID="Label1" CssClass="GeneralText" />
</p>
</div>
<div class="downloadevent">
<a href="#">
<img src="images/icon_download_event.gif" alt="Download this event to your personal calendar"
width="15" height="26" /></a><a href='<%# "events_download.ashx?EventID=" + Convert.ToString(Eval("id")) %>'>Add
this event to your personal calendar</a>
</div>
<Club:ImageThumbnail ID="thumb1" runat="server" ImageSize="Large" PhotoID='<%# Eval("photo") %>' />
<p>
<asp:Label Text='<%# Eval("description") %>' runat="server" ID="descriptionLabel" />
</p>
<div class="dashedline" ></div>
<asp:Panel ID="pnlAction" runat="server" CssClass="actionbuttons" >
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="Label2" Text="Action<br />Required" Width="80px" Font-Bold="true"
ForeColor="#cc0000" Font-Size="14px" />
</td>
<td>
<img src="images/RedArrow.jpg" alt="Red Arrow Right" />
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCert" Height="30px" Text="Check to Confirm Attendance" /><br />
<asp:CustomValidator runat="server" ID="rfvConfirm"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnkSignUp" runat="server" Text = "I will be attending this event"
OnClick="rlnkSignUp_OnClick" ToolTip="I hereby certify that I am commiting to attending this event."
/>
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel runat="server" ID="pnlActionCancel" CssClass="actionbuttons" >
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="lblDupSignup" Text="You are alredy signed up for this event" ForeColor="#cc0000" Font-Bold="true" Font-Size="14px" />
</td>
<td>
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCancel" Height="30px" Text="Check to Cancel Attendance" /><br />
<asp:CustomValidator runat="server" ID="CustomValidator1"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnCancel" runat="server" Text="I'm cancelling my participation"
OnClick="rlnCancel_OnClick" />
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:FormView>
</asp:Panel>
</div>
I've set the ViewStateMode to "Disabled". I'm just hoping it won't back fire somewhere else.
Your existing code might work if you drop an update panel and place your controls inside it.
Alternatively you can create a property in your page like
private bool myRowCount;
protected bool HasRowsMyData
{
get { return myRowCount; }
set { myRowCount=value; }
}
Then inside your selectedIndex change event
if (dt.Rows.Count == 1)
{
HasRowsMyData=true;
//DataBind your controls here
YourUpdatePanel.Update();
}
Inside your aspx on panels you can set each panel's visible property like this so whenever page is updated they will turn on/off depeding upon the result
Visible='<%#HasRowsMyData%>'
Visible='<%#!HasRowsMyData%>'
If you like to do it client side I advise jQuery's toggle function
jQuey:toggle()
This is my design
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
Font-Size="11pt" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
CellPadding="4" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="CheckAll" onclick="return check_uncheck (this );" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="ID" Visible="false" Text='<%# DataBinder.Eval (Container.DataItem, "Id") %>'
runat="server" />
<asp:CheckBox ID="deleteRec" onclick="return check_uncheck (this );" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Id" SortExpression="Id">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Id") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FileName" SortExpression="FileName">
<EditItemTemplate>
<asp:Label ID="LblFileName" runat="server" Text='<%# Eval("FileName") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LblFileName1" runat="server" Text='<%# Bind("FileName") %>'></asp:Label>
<asp:ImageButton ID="img" runat="Server" CommandName="Image" ImageUrl="~/Images/pen.png" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" />
<RowStyle BackColor="#F7F7DE" />
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:Panel ID="pnlAddEdit" runat="server" CssClass="modalPopup" Style="display: none"
Width="1000px">
<asp:Label Font-Bold="true" ID="Label4" runat="server" Text="File Data"></asp:Label>
<br />
<table align="center" width="1000px">
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="RecordTypeCode"></asp:Label>
</td>
<td>
<asp:Label ID="lblRec" runat="server" Text="Content"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblFileHeader" runat="server" Text="FileHeader"></asp:Label>
</td>
<td>
<asp:Label ID="txtCustomerID" Width="500px" MaxLength="5" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblBatchHeader" runat="server" Text="BatchHeader"></asp:Label>
</td>
<td>
<asp:Label ID="txtBatch" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="EntryDetail"></asp:Label>
</td>
<td>
<asp:Label ID="txtEntry" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" />
</td>
<td>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClientClick="return Hidepopup()" />
</td>
</tr>
</table>
</asp:Panel>
<asp:LinkButton ID="lnkFake" runat="server"></asp:LinkButton>
<cc1:ModalPopupExtender ID="popup" runat="server" DropShadow="false" PopupControlID="pnlAddEdit"
TargetControlID="lnkFake" BackgroundCssClass="modalBackground">
</cc1:ModalPopupExtender>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" />
<asp:AsyncPostBackTrigger ControlID="btnSave" />
</Triggers>
</asp:UpdatePanel>
I have taken some text boxes inside a panel when a pop-up opens but instead of that i need a gridview to be there as i have to display the content of a large file
This is my data
101 111100022 5104885671104200936A094101CapitalOne MudiamInc
5220MudiamInc A510488567CCDITServices000000110422 1111100020000001
622968765348545646565 00004000001007 rajeshk 1111100020000001
62297877654775676546546 00002888891007 rajeshk 1111100020000002
82200000020194754188000000000000000000688889A510488567 111100020000001
5220MudiamInc A510488567CCDITServices000000110422 1111100020000002
62212345678034354465677 00000864451005 swethau 1111100020000003
62212345678087664534543 00000559841011 swathiK 1111100020000004
62212345678097867546435 00000579351012 lavanyaK 1111100020000005
6221234567806754654435435 00000846761013 AnithaN 1111100020000006
82200000040049382712000000000000000000285040A510488567 111100020000002
9000002000001000000060244136900000000000000000071739300
This i have to show sequentially in an order as
RecordTyecode Content
FileHeader Starting line to be here
BatchHeader Line that come's with 5(First come line)
EntryDetail Number of 6 line has to be added on by one
BatchControl line that starts with 8 has to be here
Again if i have line starts with 5 after 8 that has to be appended like above sequence
Can any give me an idea to add this dynamically a little tricky to understand ask if any information required
This was done in winforms exact i need in web too
Just in a simple way i get this answer
Declared a hash table
static Hashtable rectype = new Hashtable();
In page load i add the following
if (rectype != null)
{
rectype.Add("1", "File Header");
rectype.Add("5", "Batch Header");
rectype.Add("6", "Entry Detail");
rectype.Add("7", "Addenda Record");
rectype.Add("8", "Batch Control");
rectype.Add("9", "File Control");
}
Here is my code when user clicks on Image button
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int id = 0;
string strLine = string.Empty;
string[] lines = null;
if (e.CommandName == "Image")
{
GridViewRow row = (GridViewRow)((Control)e.CommandSource).Parent.Parent;
Label l = (Label)GridView1.Rows[row.RowIndex].Cells[1].FindControl("Label1");
id = Convert.ToInt16(l.Text);
string selectSQL = "Select File_Data from tblachmaster WHERE Id IN (" + id + ")";
MySqlCommand cmd1 = new MySqlCommand(selectSQL);
cmd1.Parameters.Add("#_id", SqlDbType.Int).Value = id;
DataTable dt1 = GetData1(cmd1);
if (dt1 != null)
{
for (int i = 0; i < dt1.Rows.Count; i++)
{
Byte[] bytes = (Byte[])dt1.Rows[i]["File_Data"];
string text = Encoding.UTF8.GetString(bytes);
lines = Regex.Split(text, "\r\n");
strLine = convertArrayToString(lines);
}
}
DataTable table = new DataTable();
table.Columns.Add("RecordTypeCode", typeof(string));
table.Columns.Add("Content", typeof(string));
foreach (string strcontent in lines)
{
if (strcontent != string.Empty)
table.Rows.Add(rectype[(strcontent.Substring(0, 1))], strcontent);
}
dynamicGridView.DataSource = table;
dynamicGridView.DataBind();
popup.Show();
}
}
This works well for me and here is my output after clicking on Image button
You can use Ajax pop up control similar to this -
http://www.ezzylearning.com/tutorial.aspx?tid=2861497