Dictionary<obj,List<obj>> into GridView Datasource? - c#

Is there a clean, easy way to get a Dictionary<obj,List<obj2>> into a GridView Datasource in ASP.NET? If I just throw the Dictionary as-is into the GridView and am doing an Eval("Key") and Eval("Value"), I'll end up with the object name in the Eval("Value") column. I'm looking for a solution that provides a comma separated value in the Eval("Value") field.
GridView:
<SharePoint:SPGridView
id="GvItems"
runat="server"
AutoGenerateColumns="false"
width="100%"
AllowSorting="True" OnRowDataBound="GvItems_OnRowDataBound" >
<AlternatingRowStyle CssClass="ms-alternatingstrong" />
<Columns>
<asp:TemplateField ItemStyle-CssClass="ms-cbp" HeaderStyle-CssClass="ms-cbp" ItemStyle-VerticalAlign="Top">
<HeaderTemplate>
<asp:CheckBox ID="chkBoxSL"
runat="server"
AutoPostBack="true"
OnCheckedChanged="chkBoxSL_CheckedChanged"
style="margin-top:-1px; margin-bottom:-1px;" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkId"
runat="server"
class="padding-right: 15px;padding-top: 0px;padding-bottom: 0px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Web Application Zone" HeaderStyle-Width="50%" HeaderStyle-CssClass="ms-vh2-nofilter-perm" SortExpression="Key">
<ItemTemplate>
<asp:Label ID="lblZone" runat="server" Text='<%# Eval("Key") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Crawl Target" HeaderStyle-Width="50%" HeaderStyle-CssClass="ms-vh2-nofilter-perm" SortExpression="Value">
<ItemTemplate>
<asp:Label ID="lblServer" runat="server" Text='<%#Eval("Value") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
Codebehind:
{
//...
var sds = new Dictionary<SPUrlZone, List<Uri>>();
foreach (var t in webApp.SiteDataServers)
{
var uriList = new List<Uri>();
foreach (var v in t.Value)
{
uriList.Add(v);
}
sds.Add(t.Key, uriList);
}
//...
GvItems.DataSource = sds;
GvItems.DataBind();
}
protected void GvItems_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
Label label = (Label)e.Row.FindControl("lblServer");
// extract list items
string[] uris = ((KeyValuePair<SPUrlZone, List<Uri>>)e.Row.DataItem).Value.Select(x => x.ToString()).ToArray();
label.Text = string.Join(",", uris);
}
}

Check the MSDN http://msdn.microsoft.com/en-us/library/4hx47hfe%28v=vs.110%29.aspx. Currently you are accessing List only, that's the reason why it is not evaluated as you want. Optionally you can write a method in codebehind and do it manually - personally I prefer this way.
I made small example for you:
Markup:
<asp:GridView runat="server" ID="grid1">
<Columns>
<asp:BoundField HeaderText="Key" DataField="Key"></asp:BoundField>
<asp:TemplateField HeaderText="Value">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
Dictionary<string, List<Person>> data = new Dictionary<string, List<Person>>();
data.Add("Managers", new List<Person>() { new Person() { Age = 38, Name = "Bob" }, new Person() { Age = 45, Name = "Stephen" } });
data.Add("Developers", new List<Person>() { new Person() { Age = 25, Name = "Jake" }, new Person() { Age = 31, Name = "John" }, new Person() { Age = 27, Name = "Matthew" } });
grid1.RowDataBound += grid1_RowDataBound;
grid1.DataSource = data;
grid1.DataBind();
}
void grid1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.DataItem != null)
{
Label label = (Label)e.Row.FindControl("Label1");
// extract list items
string[] names = ((KeyValuePair<string, List<Person>>) e.Row.DataItem).Value.Select(x => x.Name).ToArray();
label.Text = string.Join(",", names);
}
}
protected class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
Or you can bind the values comma separated right from the beginning...Depends on your scenario.

Related

Filter a specific record from xml file to gridview asp.net

I have a xml file that contains data of employees. The design of my page is such that, when a user enters his ID the gridview displays his skills (if already exists) else nothing and proceeds to enter his data (new employee). I want to filter the record the data of employee using his ID and display in grid view.But upon using my code it throws exception stating "'System.Data.DataRow' does not contain a property with the name 'EmployeeID'". I have already bounded the templates with correct values. What seems to be the problem then?
my xml schema
-<SkillSet>
-<SkillSets>
<EmployeeID>1</EmployeeID>
<EmployeeName>abc</EmployeeName>
<PLName>xyz</PLName>
<SkillName1>Html</SkillName1>
<SkillType1>Programming</SkillType1>
<SkillProficiency1>Beginner</SkillProficiency1>
<Experience1>1</Experience1>
<Comments>Hello</Comments>
</SkillSets>
</SkillSet>
My aspx page source code:
<asp:GridView ID="grdxml" runat="server" AutoGenerateColumns="False" BackColor="White"
BorderColor="Black" BorderStyle="None" BorderWidth="1px" CellPadding="1" GridLines="Vertical"
OnSelectedIndexChanged="grdxml_SelectedIndexChanged"
onrowdeleting="grdxml_RowDeleting">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lblEmpId" runat="server" Text='<%# Bind("EmployeeID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lblEmpName" runat="server" Text='<%# Bind("EmployeeName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PL Name">
<ItemTemplate>
<asp:Label ID="lblPLName" runat="server" Text='<%# Bind("PLName")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Skill Name 1">
<ItemTemplate>
<asp:Label ID="lblSkillName1" runat="server" Text='<%# Bind("SkillName1")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Skill Type 1">
<ItemTemplate>
<asp:Label ID="lblSkillType1" runat="server" Text='<%# Bind("SkillType1")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Skill Proficiency 1">
<ItemTemplate>
<asp:Label ID="lblSkillProf1" runat="server" Text='<%# Bind("SkillProficiency1")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Experience">
<ItemTemplate>
<asp:Label ID="lblExp1" runat="server" Text='<%# Bind("Experience1")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Command"> <ItemTemplate>
<asp:LinkButton Text="Select" ID="lnkSelect" runat="server" CommandName="Select" />
<asp:LinkButton ID="lnkDelete" runat="server" CommandName="delete">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My c# code for binding grid:
private void BindGrid()
{
string filename = Server.MapPath("~/SkillSet.xml");
if (File.Exists(filename) == true)
{
try
{
string filePath = Server.MapPath("SkillSet.xml");
DataSet ds = new DataSet();
ds.ReadXml(filePath);
var skillSets = ds.Tables[0].AsEnumerable();
var query = from SkillSets in skillSets
where SkillSets.Field<string>("EmployeeID") == emplid
select SkillSets;
grdxml.DataSource = query.ToList();
grdxml.DataBind();
}
catch (Exception ex)
{
lblerror.Text = ex.ToString();
}
}
}
Full Stack Trace:
System.Web.HttpException (0x80004005): DataBinding: 'System.Data.DataRow' does not contain a property with the name 'EmployeeID'. at System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) at System.Web.UI.DataBinder.Eval(Object container, String[] expressionParts) at System.Web.UI.DataBinder.Eval(Object container, String expression) at System.Web.UI.TemplateControl.Eval(String expression) at ASP.default_aspx.__DataBinding__control130(Object sender, EventArgs e) in c:\Users\SkillSet\Default.aspx:line 230 at System.Web.UI.Control.OnDataBinding(EventArgs e) at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) at System.Web.UI.Control.DataBind() at System.Web.UI.Control.DataBindChildren() at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) at System.Web.UI.Control.DataBind() at System.Web.UI.Control.DataBindChildren() at System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) at System.Web.UI.Control.DataBind() at System.Web.UI.WebControls.GridView.CreateRow(Int32 rowIndex, Int32 dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState, Boolean dataBind, Object dataItem, DataControlField[] fields, TableRowCollection rows, PagedDataSource pagedDataSource) at System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) at System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data) at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) at System.Web.UI.WebControls.DataBoundControl.PerformSelect() at System.Web.UI.WebControls.BaseDataBoundControl.DataBind() at System.Web.UI.WebControls.GridView.DataBind() at _Default.BindGrid() in c:\Users\SkillSet\Default.aspx.cs:line 366
I have just tested this and its working fine:
var xmlStr = File.ReadAllText(Server.MapPath("YourFileName.xml"));
var str = XElement.Parse(xmlStr);
var result = str.Elements("SkillSets").Where(x => x.Element("EmployeeID").Value.Equals(emplid.ToString())).ToList();
List<Employee> mapList = new List<Employee>();
foreach (var item in result)
{
Employee obj = new Employee();
obj.EmployeeID = item.Element("EmployeeID").Value;
obj.EmployeeName = item.Element("EmployeeName").Value;
obj.PLName = item.Element("PLName").Value;
obj.SkillName1 = item.Element("SkillName1").Value;
obj.SkillType1 = item.Element("SkillType1").Value;
obj.SkillProficiency1 = item.Element("SkillProficiency1").Value;
obj.Experience1 = item.Element("Experience1").Value;
obj.Comments = item.Element("Comments").Value;
mapList.Add(obj);
}
grdxml.DataSource = mapList;
grdxml.DataBind();
And you can create class of an Employee :
public class Employee
{
private string _EmployeeID;
public string EmployeeID
{
get
{
return _EmployeeID;
}
set
{
_EmployeeID = value;
}
}
private string _EmployeeName;
public string EmployeeName
{
get
{
return _EmployeeName;
}
set
{
_EmployeeName = value;
}
}
private string _PLName;
public string PLName
{
get
{
return _PLName;
}
set
{
_PLName = value;
}
}
private string _SkillName1;
public string SkillName1
{
get
{
return _SkillName1;
}
set
{
_SkillName1 = value;
}
}
private string _SkillType1;
public string SkillType1
{
get
{
return _SkillType1;
}
set
{
_SkillType1 = value;
}
}
private string _SkillProficiency1;
public string SkillProficiency1
{
get
{
return _SkillProficiency1;
}
set
{
_SkillProficiency1 = value;
}
}
private string _Experience1;
public string Experience1
{
get
{
return _Experience1;
}
set
{
_Experience1 = value;
}
}
private string _Comments;
public string Comments
{
get
{
return _Comments;
}
set
{
_Comments = value;
}
}
}

how to multiply two columns in gridview asp.net c#

i have gridview i which 4 columns i want to multiply rate to quantity to get total i do not how to do this kindly help me, please. here is code
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound" onselectedindexchanged="GridView1_SelectedIndexChanged"
>
<Columns>
<asp:TemplateField HeaderText="Item Name">
<ItemTemplate>
<asp:DropDownList ID="cbGvProd" runat="server" Height="16px" Width="200px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="tbQty" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:TextBox ID="tbRate" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:TextBox ID="tbAmount" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code:
protected void Page_Load(object sender, EventArgs e)
{
SetGrid();
}
public void SetGrid()
{
DataTable tdTemp = new DataTable("TSno");
DataColumn dc = new DataColumn("TDc");
tdTemp.Columns.Add(dc);
for (int a = 0; a <= 24; a++)
{
tdTemp.Rows.Add(a);
}
tdTemp.AcceptChanges();
GridView1.DataSource = tdTemp;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
int qty = Convert.ToInt32(GridView1.Rows[i].Cells[1].ToString());
int rate= Convert.ToInt32(GridView1.Rows[i].Cells[2].ToString());
int total=qty * rate;
GridView1.Rows[i].Cells[3].Text = total.ToString();
}
}
Add a template field to get total, no need to do calculations on RowDataBound
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblProductTotal" runat="server"
Text='<%# ((Convert.ToInt32(Eval("Quantity")))*(Convert.ToInt32(Eval("Price"))))%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Replace Quantity and Price with the column what your are using, means from dataset or datatable
Hope this will help you.
Below is an example using jQuery. Have a look at the code below and understand how it works then make changes to your application
Code behind:
public partial class GridTwo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<OrderLineItem> lineItems = new List<OrderLineItem>();
lineItems.Add(new OrderLineItem { Price = 10.00M, Quantity = 0, ItemTotal = 0.00M });
lineItems.Add(new OrderLineItem { Price = 100.00M, Quantity = 0, ItemTotal = 0.00M });
lineItems.Add(new OrderLineItem { Price = 5.00M, Quantity = 0, ItemTotal = 0.00M });
GridView1.DataSource = lineItems;
GridView1.DataBind();
}
}
public class OrderLineItem
{
public decimal Price { get; set; }
public int Quantity { get; set; }
public decimal ItemTotal { get; set; }
}
.ASPX:
<head runat="server">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(".QuantityClass").on('change keyup paste', function () {
//Ctrl+Shift+J in Google Chrome to bring up the console which allows you to debug javascript
debugger;
var textBox = this;
var quantity = $(textBox).val();
var tableRows = $(textBox).parent().parent().children();
if (quantity != "") {
var price = tableRows[0].children[0].innerHTML;
var itemTotal = price * quantity;
tableRows[2].children[0].innerHTML = itemTotal;
}
else
tableRows[2].children[0].innerHTML = "";
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" Text='<%# Bind("Price")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" CssClass="QuantityClass" runat="server" Text='<%# Bind("Quantity")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Item Total">
<ItemTemplate>
<asp:Label ID="lblItemTotal" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
Output:

DropdownList with Checkbox in a GridView

Here is my current grid view.
<asp:GridView ID="grdIndexGroupMap" runat="server" AutoGenerateColumns="False" DataKeyNames="IndexName"
OnRowCancelingEdit="grdIndexGroupMap_RowCancelingEdit" OnRowDataBound="grdIndexGroupMap_RowDataBound"
OnRowEditing="grdIndexGroupMap_RowEditing" OnRowUpdating="grdIndexGroupMap_RowUpdating"
OnRowCommand="grdIndexGroupMap_RowCommand" ShowFooter="True" OnRowDeleting="grdIndexGroupMap_RowDeleting"
CellPadding="1" CellSpacing="1" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<%--IndexName--%>
<asp:TemplateField HeaderText="IndexName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="cmbIndexName" runat="server" DataTextField="LocationName" DataValueField="IndexId"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblIndexName" runat="server" Text='<%# Eval("IndexName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="cmbNewIndexName" runat="server" DataTextField="IndexName" DataValueField="IndexId"></asp:DropDownList>
</FooterTemplate>
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
</asp:TemplateField>
</Columns>
</asp:GridView>
How do replace the DropDownList with a dropdown where I can select multiple items?
A checkboxlist in dropdownlist or a listbox with multiselect in dropdown. When selected will show comma seperated values.
Tried a couple of ways but wont work.
here is my databound method:
protected void grdIndexGroupMap_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList cmbIndexName = (DropDownList)e.Row.FindControl("cmbIndexName");
if (cmbIndexName != null)
{
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
cmbIndexName.SelectedValue = grdIndexGroupMap.DataKeys[e.Row.RowIndex].Values[1].ToString();
}
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList cmbNewIndexName = (DropDownList)e.Row.FindControl("cmbNewIndexName");
cmbNewIndexName.DataSource = _Indexes;
cmbNewIndexName.DataBind();
}
}
I am using ASP.Net, C#
How about:
<asp:TemplateField HeaderText="IndexName" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:PlaceHolder id="phListContainer" runat="server" />
</EditItemTemplate>
then in your code-behind:
if (e.Row.RowType == DataControlRowType.DataRow)
{
phListContainer = (PlaceHolder)e.Row.FindControl(phListContainer);
if (phListContainer != null)
{
//Adding a DropDownList
var cmbIndexName = new DropDownList();
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
cmbIndexName.SelectedValue = grdIndexGroupMap.DataKeys[e.Row.RowIndex].Values[1].ToString();
phListContainer.Controls.Add(cmbIndexName);
// OR
//Adding a CheckBoxList;
cmbIndexName = new CheckBoxList();
cmbIndexName.DataSource = _Indexes;
cmbIndexName.DataTextField = "IndexName";
cmbIndexName.DataValueField = "IndexId";
cmbIndexName.DataBind();
phListContainer.Controls.Add(cmbIndexName);
}
}
Then you can get the controls by
var cbList = (CheckBoxList)e.Row.FindControl(phListContainer).Controls[0];
and then you can loop through and find the checked boxes
for(int i = 0; i < cbList.Items.Count; ++i)
{
if(cbList.Items[i].Selected)
//Do stuff
}

not working paging functionality of my gridview

i put my problem here ,it is shown in screenshot.
my code is below.
code for .aspx file
<asp:GridView ID="grid" runat="server" DataKeyNames="EventID" AutoGenerateColumns="false"
Width="100%" AllowPaging="True" OnRowDataBound="grid_RowDataBound" PageSize="3"
OnRowEditing="grid_RowEditing" OnRowUpdating="grid_RowUpdating" OnRowCancelingEdit="grid_RowCancelingEdit"
OnPageIndexChanging="grid_PageIndexChanging">
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NextPreviousFirstLast"
NextPageText="Next" PreviousPageText="Prev" PageButtonCount="3" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
Client Name
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblClientName" runat="server" Text='<%# Eval("ClientName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtClientName" runat="server" Text='<%# Eval("ClientName")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Event Name
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblEventName" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEventName" runat="server" Text='<%# Eval("Name")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Invited Persons
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblNoOfInvitees" runat="server" Text='<%# Eval("No_Of_Invitees")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNoOfInvitees" runat="server" Text='<%# Eval("No_Of_Invitees")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Total Invitees
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblTotalInvitees" runat="server" Text='<%# Eval("Total_Invitees")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtTotalInvitees" runat="server" Text='<%# Eval("Total_Invitees")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Extra Invitees
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblExtraInvitees" runat="server" Text='<%# Eval("Extra_Invitees")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtExtraInvitees" runat="server" Text='<%# Eval("Extra_Invitees")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
Confirmed
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblConfirmed" runat="server" Text='<%# Eval("Extra_Invitees")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtConfirmed" runat="server" Text='<%# Eval("Extra_Invitees")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" HeaderText="Edit" />
<%-- <asp:TemplateField>
<HeaderTemplate>
Delete
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton CommandName="Delete" ID="btnDelete" runat="server" Text="Delete"
OnClientClick="return validate();" />
<script type="text/javascript" language="javascript">
function validate() {
return confirm('Are you sure want to delete this user ?');
}
</script>
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
Showing
<asp:Label ID="PageIdxLabel" Text="1" runat="server" />
to
<asp:Label ID="PageRowCountLabel" runat="server" />
of
<asp:Label ID="PageTotalLabel" runat="server" Text="Label" />
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
and aspx.cs file coding is here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataLayer;
using System.Data.Linq;
using System.Web.Extensions;
using System.Web.UI.WebControls.WebParts;
namespace EventManagerApp
{
public partial class EventList : System.Web.UI.Page
{
EventManagerDataContext db = new EventManagerDataContext();
[System.Web.Services.WebMethod]
public static string[] GetNames(string prefixText)
{
EventManagerDataContext db = new EventManagerDataContext();
return db.EMR_EVENTs.Where(n => n.Name.StartsWith(prefixText)).OrderBy(n => n.Name).Select(n => n.Name).ToArray();
//return db.EMR_CLIENTs.Where(n => n.Name.StartsWith(prefixText)).OrderBy(n => n.Name).Select(n => n.Name).ToArray();
}
protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
{
grid.EditIndex = e.NewEditIndex;
grdBind();
}
protected void grid_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grid.EditIndex = -1;
grdBind();
}
protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int EventID = Convert.ToInt32(grid.DataKeys[e.RowIndex].Value.ToString());
string ClientName = ((TextBox)grid.Rows[e.RowIndex].FindControl("txtClientName")).Text;
string EventName = ((TextBox)grid.Rows[e.RowIndex].FindControl("txtEventName")).Text;
int TotalInvitees = int.Parse(((TextBox)grid.Rows[e.RowIndex].FindControl("txtTotalInvitees")).Text);
int ExtraInvitees = int.Parse(((TextBox)grid.Rows[e.RowIndex].FindControl("txtExtraInvitees")).Text);
int Confirmed = int.Parse(((TextBox)grid.Rows[e.RowIndex].FindControl("txtConfirmed")).Text);
EventManagerDataContext db = new EventManagerDataContext();
var q = (from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
where a.EventID == EventID
select a).First();
q.EMR_CLIENT.Name = ClientName;
q.Name = EventName;
q.No_Of_Invitees = TotalInvitees;
q.Extra_Invitees = ExtraInvitees;
q.Total_Invitees = ExtraInvitees + TotalInvitees;
db.SubmitChanges();
grid.EditIndex = -1;
grdBind();
}
protected void Page_Load(object sender, EventArgs e)
{
lblwelcometext.Text = (string)(Session["name"]);
try
{
if (!IsPostBack)
{
grdBind();
bindClients();
}
}
catch (Exception ex)
{
throw ex;
}
}
public class DALClass
{
private static EventManagerDataContext db = new EventManagerDataContext() { CommandTimeout = 36000 };
public static List<EMR_CLIENT> GetClients()
{
return db.EMR_CLIENTs.ToList();
}
}
protected void bindClients()
{
drpClient.DataSource = DALClass.GetClients();
drpClient.DataTextField = "Name";
drpClient.DataValueField = "ClientID";
drpClient.DataBind();
string Name = drpClient.SelectedItem.Value;
}
protected void grdBind()
{
try
{
EventManagerDataContext db = new EventManagerDataContext();
if (txtSearchEvent.Text == "")
{
var q = from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
select new
{
ClientName = b.Name,
ClientID = a.ClientID,
Name = a.Name,
No_Of_Invitees = a.No_Of_Invitees,
Extra_Invitees = a.Extra_Invitees,
Total_Invitees = a.Extra_Invitees + a.No_Of_Invitees,
EventID = a.EventID
};
grid.DataSource = q.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
else
{
var data = from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
where a.Name.StartsWith(txtSearchEvent.Text.Trim())
select new
{
ClientName = b.Name,
ClientID = a.ClientID,
Name = a.Name,
No_Of_Invitees = a.No_Of_Invitees,
Extra_Invitees = a.Extra_Invitees,
Total_Invitees = a.Extra_Invitees + a.No_Of_Invitees,
EventID = a.EventID
};
grid.DataSource = data.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
}
catch
{
throw;
}
}
protected void txtSearchEvent_TextChanged(object sender, EventArgs e)
{
grdBind();
}
protected void drpPageSize_SelectedIndexChanged(object sender, EventArgs e)
{
grid.PageSize = int.Parse(drpPageSize.SelectedItem.Text);
grdBind();
}
protected void drpClient_SelectedIndexChanged(object sender, EventArgs e)
{
if (drpClient.SelectedIndex == 0)
{
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grdBind();
}
else
{
var q = from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
where a.ClientID == int.Parse(drpClient.SelectedValue.ToString())
select new
{
ClientName = b.Name,
ClientID = a.ClientID,
Name = a.Name,
No_Of_Invitees = a.No_Of_Invitees,
Extra_Invitees = a.Extra_Invitees,
Total_Invitees = a.Extra_Invitees + a.No_Of_Invitees,
EventID = a.EventID
};
grid.DataSource = q.ToList();
grid.PageSize = int.Parse(drpPageSize.SelectedValue);
grid.DataBind();
}
}
protected void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grdBind();
}
protected void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
EventManagerDataContext db = new EventManagerDataContext();
var q = from a in db.EMR_EVENTs
join b in db.EMR_CLIENTs on a.ClientID equals b.ClientID
select new
{
ClientName = b.Name,
ClientID = a.ClientID,
Name = a.Name,
No_Of_Invitees = a.No_Of_Invitees,
Extra_Invitees = a.Extra_Invitees,
Total_Invitees = a.Extra_Invitees + a.No_Of_Invitees,
EventID = a.EventID
};
PageTotalLabel.Text = q.Count().ToString();
PageRowCountLabel.Text = grid.Rows.Count.ToString();
// PageIdxLabel.Text = grid.PageIndex.ToString();
}
}
}
so my problem is i want update pageindex value as per click on next and previous button.
This is the solution of my question ,i solved it my self.
Thanks stackoverflow.
int pagetotal = q.Count();
int pagerowcount = (grid.PageIndex * grid.PageSize) + grid.Rows.Count;
PageIdxLabel.Text = ((grid.PageIndex * grid.PageSize) + 1).ToString() + "to " + Convert.ToString(pagerowcount) + "of" + (pagetotal).ToString();

Row Databound issue when changing Container.DataItem value in a gridview

I am using a gridview to display on a buttonClick in asp.net using c#.
DataSet dsnew = new businessLogic.Biz().getData();
if (dsnew != null && dsnew.Tables[0].Rows.Count > 0)
{
DataView myDataView = new DataView();
myDataView = dsnew.Tables[0].DefaultView;
grdDetail.DataSource = myDataView;
grdDetail.DataBind();
}
and on a rowDataBound, depending on the condition, i want to change the dataitem container value. I am doing it in the following way but the issue is that all the rows have the paymentmethod of the last row in the dataset.
<asp:TemplateField ItemStyle-Width="70" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="lblPaymentMethod" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"SellingPaymentMethod") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
protected void grdDetail_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
return;
}
foreach (DataRow dtrCurrentRow in (((System.Data.DataView)grdDetail.DataSource)).Table.Rows)
{
//DataRow row = (DataRow)e.Row.DataItem;
Label lblPaymentMethod = e.Row.FindControl("lblPaymentMethod") as Label;
if (Condition1))
{
lblPaymentMethod.Text = dtrCurrentRow["SellingPaymentMethod"].ToString();
}
else if (Condition 2)
{
lblPaymentMethod.Text = dtrCurrentRow["DeliveryPaymentmethod"].ToString();
}
}
Instead of using rowDataBound event to check what value to display you may try to directly control visibility or directly set text property of your columns! I did a small example for you, which could be easily adapted to your needs!
ASPX
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Visible='<%# CheckCondition1(Eval("ID")) %>' Text='<%# Bind("ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductName">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Visible='<%# CheckCondition2(Eval("ProductName")) %>' Text='<%# Bind("ProductName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="thirdColumn">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# GetValue(Eval("ID")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="forthColumn">
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# GetValue(Eval("ID"), "staticValue", Eval("ProductName")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CodeBehind
public bool CheckCondition1(object ID)
{
return ID.ToString() != "2";
}
public bool CheckCondition2(object ProductName)
{
return ProductName.ToString() != "jklö";
}
public string GetValue(object ID)
{
// check condition here
// ...
// and return according value
return ID.ToString() + " is your ID";
// eg
//if (Condition1))
// return dtrCurrentRow["SellingPaymentMethod"].ToString();
//else if (Condition 2)
// return dtrCurrentRow["DeliveryPaymentmethod"].ToString();
}
public string GetValue(object ID, object firstValue, object secondValue)
{
if (ID.ToString() == "2")
return firstValue.ToString();
else
return secondValue.ToString();
}
CodeBehind to show demo values
// assume there is a class Products with id and ProductName
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Product> products = new List<Product>();
products.Add(new Product() { ID = 1, ProductName = "asdf" });
products.Add(new Product() { ID = 2, ProductName = "asdf" });
products.Add(new Product() { ID = 3, ProductName = "jklö" });
products.Add(new Product() { ID = 4, ProductName = "asdf" });
gvProducts.DataSource = products;
gvProducts.DataBind();
}
}
Should result in this:.

Categories

Resources