not working paging functionality of my gridview - c#

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();

Related

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:

Grid view locking button by user id

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")) %>

Dictionary<obj,List<obj>> into GridView Datasource?

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.

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:.

Hide/show table in gridview on button click event

I have project on recruitment.In this project, at one form I have a grid view which contains details of all vacancies. Along with this there is button. When user clicks on this button, available interview schedule for that particular vacancy will be visible in another grid below that row. What I did is I have placed grid view inside table and table is initially invisible. When user clicks on the image button, at that time I tried to find table from the grid view but it can not be found.
Here is the code of my .aspx page
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
<table class="formtTbl" width="100%">
<tr>
<td width="10%">
</td>
<td>
</td>
<td width="10%">
</td>
</tr>
<tr>
<td>
</td>
<td align="center" class="tdtitle">
Open vacancies
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:ImageButton ID="addVacancyBtn" runat="server"
ImageUrl="~/Resources/add.png" onclick="addVacancyBtn_Click" />
Add New Vacancy</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:GridView ID="VacancyGrid" runat="server" CssClass="mGrid"
AutoGenerateColumns="False" onrowcommand="VacancyGrid_RowCommand">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ScheduleBtn" runat="server"
ImageUrl="~/Resources/01.gif"
ToolTip="View Interview Schedule" Width="20px"
CommandName="View Schedule" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="VacId" DataField="VacId" />
<asp:BoundField HeaderText="Title" DataField="VacTitle" />
<asp:BoundField HeaderText="Open" DataField="TotalOpening" />
<asp:BoundField HeaderText="Criteria" DataField="criteria" />
<asp:BoundField HeaderText="Key Skills" DataField="KeySkills" />
<asp:BoundField HeaderText="Exp" DataField="RequiredExperience" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="editBtn" runat="server"
ImageUrl="~/Resources/art-knife.png" Width="20px"
CommandName="Edit" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
<EditItemTemplate>
Edit
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="statusLbl" runat="server" Text="Label"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<table id="ScheduleTable" visible="false">
<tr id="abc" visible="false">
<td colspan="10">
<asp:GridView ID="scheduleGrid" runat="server" Visible="False"
AutoGenerateColumns="False" onrowcommand="scheduleGrid_RowCommand">
<Columns>
<asp:BoundField DataField="VacId" HeaderText="ID" />
<asp:BoundField DataField="VacTitle" HeaderText="Title" />
<asp:BoundField DataField="InterviewTime" HeaderText="Interview Date & Time" />
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="viewIntervieweesBtn" runat="server"
ImageUrl="~/Resources/document.png" ToolTip="View interiviewees" Width="20px"
CommandName="View Interviewees" CommandArgument="<%#((GridViewRow)Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="ScheduleNotifyLbl" runat="server" Visible="false"></asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerStyle CssClass="pgr" />
</asp:GridView>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td align="left">
<asp:Label ID="notificationLbl" runat="server" Font-Size="X-Large"
ForeColor="Red" Text="Label" Visible="False"></asp:Label>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
</table>
</asp:Content>
//Here is the code for my .aspx.cs page
public partial class Department_VacancyList : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
DataTable VacancyTable = null;
try
{
if (!IsPostBack)
{
if (Request.QueryString["status"] != null)
{
// strStatus = Request.QueryString["status"];
Session.Add("strStatus", Request.QueryString["status"]);
}
if (Session["OpResult"] != null)
{
notificationLbl.Visible = true;
if (Session["OpResult"].ToString() == "InsertSuceess")
notificationLbl.Text = "New Vacancy Has Been Created Successfully";
if (Session["OpResult"].ToString() == "InsertFail")
notificationLbl.Text = "An Error Occured While Creating New Vacancy..";
if (Session["OpResult"].ToString() == "EditSuccess")
notificationLbl.Text = "Your Changes Has Been Saved Successfully";
if (Session["OpResult"].ToString() == "EditFail")
notificationLbl.Text = "An Error Occured While Saving Changes...";
}
using (VacancyMasterClass VacMaster = new VacancyMasterClass())
{
if (Session["strStatus"].ToString() == "1")//All Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1");//Change Here.
else if (Session["strStatus"].ToString() == "2")//Open Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1 and Status=0");//Change Here.
else if (Session["strStatus"].ToString() == "3")//Closed Vacancies
VacancyTable = VacMaster.getTable("and DeptId=1 and CompId=1 and Status=1");//Change Here.
VacancyGrid.DataSource = VacancyTable;
VacancyGrid.DataBind();
VacancyGrid.ControlStyle.Width = 650;
VacancyGrid.Columns[0].ItemStyle.Width = 20;
VacancyGrid.Columns[1].ItemStyle.Width = 10;
VacancyGrid.Columns[2].ItemStyle.Width = 150;
VacancyGrid.Columns[3].ItemStyle.Width = 20;
VacancyGrid.Columns[4].ItemStyle.Width = 190;
VacancyGrid.Columns[5].ItemStyle.Width = 190;
VacancyGrid.Columns[6].ItemStyle.Width = 20;
VacancyGrid.Columns[7].ItemStyle.Width = 30;
VacancyGrid.Columns[8].ItemStyle.Width = 30;
VacancyGrid.Columns[9].ItemStyle.Width = 0;
VacancyGrid.Columns[1].Visible = false;
if (Session["strStatus"].ToString() == "1" || Session["strStatus"].ToString() == "3")
{
VacancyGrid.Columns[7].Visible = false;
VacancyGrid.Columns[0].Visible = false;
for (int intRowcount = 0; intRowcount < VacancyTable.Rows.Count; intRowcount++)
{
Label StatusLbl = (Label)VacancyGrid.Rows[intRowcount].Cells[6].FindControl("statusLbl");
if (VacancyTable.Rows[intRowcount]["Status"].ToString() == "False")
{
StatusLbl.ForeColor = Color.Green;
StatusLbl.Text = "Open";
}
else
{
StatusLbl.ForeColor = Color.Red;
StatusLbl.Text = "Closed";
}
}
}
else if (Session["strStatus"].ToString() == "2")
VacancyGrid.Columns[8].Visible = false;
}
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "Page_Load", ex.Message);
}
finally
{
Session.Remove("OpResult");
}
}
//protected void VacancyGrid_RowEditing(object sender, GridViewEditEventArgs e)
//{
// int intOpMode = 2;//Edit Mode
// int intVacId = Convert.ToInt32(VacancyGrid.Rows[e.NewEditIndex].Cells[1].Text);
// Response.Redirect("create_vacancyfrm.aspx?VacId="+intVacId+"&OpMode="+intOpMode);
//}
protected void addVacancyBtn_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
int intOpMode = 1;//Edit Mode
int intVacId = 0;
Response.Redirect("create_vacancyfrm.aspx?DeptId=1&CompId=1&VacId=" + intVacId + "&OpMode=" + intOpMode);//Change Here
}
protected void VacancyGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
DataTable InterviewScheduleTable = null;
int intVacid = 0;
try
{
if (e.CommandName == "View Schedule")
{
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow Row = VacancyGrid.Rows[intRowIndex];
//Table ScheduleTable = (Table)Row.FindControl("ScheduleTable");
intVacid = Convert.ToInt32(Row.Cells[1].Text);
GridView scheduleGrid = (GridView)Row.FindControl("scheduleGrid");
Label ScheduleNotifyLbl = (Label)Row.FindControl("ScheduleNotifyLbl");
if (scheduleGrid.Visible == false)
{
using (vwVacInterviewShcedule oInterviewSchedule = new vwVacInterviewShcedule())
{
InterviewScheduleTable = oInterviewSchedule.getTable("and VacId=" + intVacid);
if (InterviewScheduleTable.Rows.Count > 0)
{
scheduleGrid.Visible = true;
scheduleGrid.DataSource = InterviewScheduleTable;
scheduleGrid.DataBind();
scheduleGrid.ControlStyle.Width = 650;
scheduleGrid.Columns[0].ItemStyle.Width = 10;
scheduleGrid.Columns[1].ItemStyle.Width = 300;
scheduleGrid.Columns[2].ItemStyle.Width = 250;
scheduleGrid.Columns[3].ItemStyle.Width = 90;
}
else
{
if (ScheduleNotifyLbl.Visible == false)
{
ScheduleNotifyLbl.Visible = true;
ScheduleNotifyLbl.Text = "Interview is yet to schedyule for this vacancy";
}
else
{
ScheduleNotifyLbl.Visible = false;
}
}
}
}
else
{
scheduleGrid.Visible = false;
}
}
ViewState.Add("VacId", intVacid);
if (e.CommandName == "Edit")
{
int intOpMode = 2;
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow Row = VacancyGrid.Rows[intRowIndex];
int intVacId = Convert.ToInt32(Row.Cells[1].Text);
Response.Redirect("create_vacancyfrm.aspx?VacId=" + intVacId + "&OpMode=" + intOpMode);
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "VacancyGrid_RowCommand", ex.Message);
}
finally
{
InterviewScheduleTable = null;
}
}
protected void scheduleGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
foreach (GridViewRow Row in VacancyGrid.Rows)
{
GridView ScheduleGrid = (GridView)Row.FindControl("scheduleGrid");
if (e.CommandName == "View Interviewees")
{
int intRowIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow ScheduleGridRow = ScheduleGrid.Rows[intRowIndex];
int intVacId = Convert.ToInt32(ScheduleGridRow.Cells[3].Text);
Session.Add("Time",ScheduleGridRow.Cells[2].Text);
Response.Redirect("~/Department Head/Schedulefrm.aspx?VacId="+intVacId);
}
}
}
catch (Exception ex)
{
CommonProcedures.WriteErrorLog("Department_VacancyList", "scheduleGrid_RowCommand", ex.Message);
}
}
}
Please show me my problem...
You have provided too much code, that can't be read easily. You have to narrow it down to a specific point.
Let me try to help you on your specific problem.
If you set the control visible=false it will not render at client side and you can't make that control visible later on in client side. Have a look at this similar thread to get an idea how to proceed: Want to make the visibility true from client side of the control which made invisible from server side

Categories

Resources