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:
Related
I have a gridview in my project where like twitter you can see other peoples post but i want to allow users to change there posts and because of that near every post i putted an edit button. Now my problem is i cant lock the button if the user didnt post that tweet. can you show me how i can check if the users id (a given variable) matches the tweet user id (hidden field) i thought on using the for each loop but i cant succeed using it.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
ShowHeader="False" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" OnRowCancelingEdit="GridView1_Cancel"
onrowupdating="GridView1_RowUpdating"
onrowdeleting="GridView1_RowDeleting" >
<Columns>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="lbl_Username" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tweet">
<ItemTemplate>
<asp:Label ID="lbl_Tweet" runat="server" Text='<%#Eval("TweetText") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="Tbx_Tweet" runat="server" Text='<%#Eval("TweetText") %>' ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image ID="Pic" runat="server" ImageUrl='<%#"~/UploadedImages/"+Eval("PicName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Like">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Like" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ReTweet">
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="ReTweet" CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TweetID" Visible="true">
<ItemTemplate>
<asp:Label ID="lbl_TweetID" runat="server" Text='<%#Eval("TweetID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID" Visible="true">
<ItemTemplate>
<asp:Label ID="lbl_UserID" runat="server" Text='<%#Eval("UserID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField >
<ItemTemplate >
<asp:LinkButton ID="Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="Delete" runat="server" Text="Delete" CommandName="Delete" />
<asp:LinkButton ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:LinkButton ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class Tweets : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
bool f = true;
if (!IsPostBack)
{
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//Response.End();
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// row.Cells[7].Visible = false;
//}
}
BindGridview();
//foreach (GridViewRow row in GridView1.Rows)
//{
// Label l = row.FindControl("UserID") as Label;
// Response.Write(l.Text);
// //if (int.Parse(l.Text.ToString()) != 1)
// //{
// // Response.End();
// // row.Cells[7].Visible = false;
// //}
//}
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int userId = 1;
if (e.CommandName == "Like")
{
int index = Convert.ToInt32(e.CommandArgument);
Label l = GridView1.Rows[index].FindControl("lbl_TweetID") as Label;
TweetHelper.Like(int.Parse(l.Text), userId);
}
if (e.CommandName == "ReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
Label l = GridView1.Rows[index].FindControl("lbl_TweetID") as Label;
TweetHelper.ReTweet(int.Parse(l.Text), userId);
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridview();
}
public void BindGridview()
{
int userId = 1;
ServiceReference1.WebServiceSoapClient objWs = new ServiceReference1.WebServiceSoapClient();
DataSet ds = objWs.SelectTweets(userId, false);
DataTable dt = ds.Tables[0];
GridView1.DataSource = dt;
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// // row.Cells[7].Visible = false;
//}
Response.Write(l.Text);
}
//int i = 0,x=0,y=0;
//DataTable dt1 = new DataTable();
//foreach (DataRow row in dt.Rows)
//{
// foreach (object obj in row.ItemArray)
// {
// dt1.Rows.Add(dt.Rows[x][4]);
// x++;
// }
//}
//foreach (DataRow row in dt1.Rows)
//{
// foreach (object obj in row.ItemArray)
// {
// if (obj.ToString() == userId.ToString())
// {
// GridView1.Rows[i].FindControl("Buttons").Visible = true;
// }
// else
// {
// GridView1.Rows[i].FindControl("Buttons").Visible = false;
// }
// i++;
// }
//}
GridView1.DataBind();
foreach (GridViewRow row in GridView1.Rows)
{
Label l = row.FindControl("UserID") as Label;
//if (int.Parse(l.Text.ToString()) != 1)
//{
// Response.End();
// // row.Cells[7].Visible = false;
//}
Response.Write(l.Text);
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label TweetID = GridView1.Rows[e.RowIndex].FindControl("lbl_TweetID") as Label;
TextBox TweetText = GridView1.Rows[e.RowIndex].FindControl("Tbx_Tweet") as TextBox;
TweetHelper.Updatetweet(int.Parse(TweetID.Text), TweetText.Text);
GridView1.EditIndex = -1;
BindGridview();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
}
}
You have more options to do it.
Create RowDataBound event handler and set up edit button Visibile/Enable property:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label userIdLbl = (Label)e.Row.FindControl("lbl_UserID");
LinkButton editBt = (LinkButton)e.Row.FindControl("Edit");
editBt.Visible = currentUserId == Convert.ToInt32(userIdLbl.Text);
}
}
Create a method in your code behind to check if the userId is currentUserId and add the attribute Visible/Enable to your edit button in gridview template:
Visible='<%# IsCurentUserId((int)Eval("UserID")) %>
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
}
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.
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();
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:.