I have 4 values in List I want to bind that values in gridview row of first column
I tried with the below code but it is overwriting with the last value of list in every row
Code .aspx
<asp:GridView ID="gridActivity" runat="server" AllowSorting="true" AutoGenerateColumns="false"
CellPadding="5" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84" Height="171px" style="margin-left: 0px; margin-right: 0px" Width="780px">
<FooterStyle ForeColor="#8C4510"
BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center"></PagerStyle>
<HeaderStyle Width="10px" Wrap="false" ForeColor="White" Font-Bold="True"
BackColor="SteelBlue"></HeaderStyle>
<Columns>
<asp:TemplateField HeaderText="Activities">
<ItemTemplate>
<asp:Label ID="lblActivity" runat="server" Text='<%#Eval("ActivityName") %>' CssClass="columnStyle"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Monday">
<ItemTemplate>
<asp:TextBox ID="txtMon" runat="server" Width ="100%"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tuesday">
<ItemTemplate>
<asp:TextBox ID="txtTue" runat="server" Width ="100%"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Wednesday">
<ItemTemplate>
<asp:TextBox ID="txtWed" runat="server" Width ="100%"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Thursday">
<ItemTemplate>
<asp:TextBox ID="txtThu" runat="server" Width ="100%"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Friday">
<ItemTemplate>
<asp:TextBox ID="txtFri" runat="server" Width ="100%"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Saturday">
<ItemTemplate>
<asp:TextBox ID="txtSat" runat="server" Width ="100%"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sunday">
<ItemTemplate>
<asp:TextBox ID="txtSun" runat="server" Width ="100%"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" Width ="100%"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code .cs:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DbConnection.Open();
gridActivity.DataSource = Application["listActivity"];
gridActivity.DataBind();
DbConnection.Close();
}
if (Application["mondayValues"] != null)
{
//Here I can get all the values
foreach (string mon in Application["mondayValues"] as List<string>)
{
//Here is the problem
foreach (GridViewRow row in gridActivity.Rows)
{
TextBox txtMon = (TextBox)row.FindControl("txtMon");
txtMon.Text = mon;
}
}
}
}
In the below code I can get all the Monday row values and stored into Application["monday"]
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach(GridViewRow row in gridActivity.Rows)
{
TextBox txtMon = (TextBox)row.FindControl("txtMon");
Application["mondayValues"] = txtMon.Text;
mondayData = new MondayData { MondayValue = txtMon.Text };
listMonday.Add(txtMon.Text);
}
Application["mondayValues"] = listMonday;
}
Any ideas? Thanks in advance.
Try this and see what happens
if (Application["mondayValues"] != null)
{
List<string> monValues = Application["mondayValues"] as List<string>;
for (int i = 0; i <= gridActivity.Rows.Count-1; i++)
{
GridViewRow row = gridActivity.Rows[i];
TextBox txtMon = (TextBox)row.FindControl("txtMon");
txtMon.Text = monValues[i];
}
}
foreach (string mon in Application["mondayValues"] as List<string>)
{
//Here is the problem
foreach (GridViewRow row in gridActivity.Rows)
{
TextBox txtMon = (TextBox)row.FindControl("txtMon");
txtMon.Text = mon;
}
}
In the above code you last value in the list Application["mondayValues"], is being assigned to all the text boxes txtMon because you are iterating all the rows and assigning them value, any change made in earlier iteration is being lost.
This code to me is not making much of sense, can you include more details of what you are trying to to, so that we can look into the same.
Related
I have a gridview with a label and a commandfield for edit.
I want to disable the commandfield if the label contains today's date.
All commandfields of empty labels should be enabled.
How can I achieve that?
Thanks
Aspx -
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Schedule Date">
<ItemTemplate>
<asp:Label ID="schedule" runat="server" Text='<%# Eval("Date","{0:dd-MMM-yy}") %>'></asp:Label>
</ItemTemplate>
<asp:CommandField ShowEditButton="true" EditText="Click here to Schedule/Re-Schedule" UpdateText="Submit" HeaderText="Schedule/Re-Schedule" />
</Columns>
</asp:GridView>
its better if you use command field as linkButton:
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False"
onrowdatabound="gv_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Schedule Date">
<ItemTemplate>
<asp:Label ID="schedule" runat="server" Text='10:25-02-2015'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False"
CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
then you can use row data bound event:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label schedule = (Label)e.Row.FindControl("schedule");
LinkButton LinkButton1 = (LinkButton)e.Row.FindControl("LinkButton1");
if (schedule.Text == string.Empty)
{
LinkButton1.Enabled = false;
}
else
{
LinkButton1.Enabled = true;
}
}
}
This will help you!
I have a footer template in my gridview which allows users to add new items to the grid. Since they don't want to go below the page each time to add and they want to bring that footer row as the first row of the gridview.
ASPX:
<asp:GridView ID="gvApplication" runat="server" AutoGenerateColumns="False" HorizontalAlign="center"
ShowFooter="True" CellPadding="3" GridLines="Both" CssClass="contentfont" ShowHeaderWhenEmpty="True"
EmptyDataText="No Records Found" OnRowDataBound="gvApplication_RowDataBound"
OnRowDeleting="gvApplication_RowDeleting" OnRowCommand="gvApplication_RowCommand"
DataKeyNames="ID,Group,App_Name" Width="100%">
<Columns>
<asp:TemplateField HeaderText="ID"
<asp:Label ID="lblID" runat="server" Text='<%# Bind("[ID]") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlID" runat="server" Width="150px" AutoPostBack="True"
OnSelectedIndexChanged="ddlID_SelectedIndexChanged" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Application Group">
<ItemTemplate>
<asp:Label ID="lblAppGrp" runat="server" Text='<%# Bind("[Group]") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlGroup" runat="server" Width="150px" AutoPostBack="True"
OnSelectedIndexChanged="ddlGroup_SelectedIndexChanged" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Application Name">
<ItemTemplate>
<asp:Label ID="lblAppName" runat="server" Text='<%# Bind ("[App_Name]") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddlApp" runat="server" Width="150px" AutoPostBack="True"
OnSelectedIndexChanged="ddlApp_SelectedIndexChanged" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/delete.gif"
ToolTip="Delete" OnClientClick="return confirm('Are you sure want to Delete');" />
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkAdd" Width="65px" runat="server" CausesValidation="False"
CommandName="AddNew" Text="Link Code" ForeColor="#3f6da2" Font-Bold="true">
</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<RowStyle Wrap="False" />
<HeaderStyle Wrap="False" BackColor="#5B95CF" ForeColor="White" Height="25px" BorderStyle="Ridge" />
<FooterStyle BackColor="#D1DDF1" ForeColor="White" Font-Bold="True" />
</asp:GridView>
CS:
public void gvApplication_RowDataBound(object sender, GridViewRowEventArgs e)
{
DataRowView drview = e.Row.DataItem as DataRowView;
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlID = (DropDownList)e.Row.FindControl("ddlID");
ddlID .DataSource = AppDataRepository.GetID();
ddlID .DataValueField = "ID";
ddlID .DataTextField = "ID";
ddlID .DataBind();
ddlID .Items.Insert(0, new ListItem("--Select ID--", "0"));
ddlID .SelectedIndex = 0;
DropDownList ddlGroup = (DropDownList)e.Row.FindControl("ddlGroup");
ddlGroup.DataSource = AppDataRepository.GetGroup();
ddlGroup.DataValueField = "Group";
ddlGroup.DataTextField = "Group";
ddlGroup.DataBind();
ddlGroup.Items.Insert(0, new ListItem("--Select Group--", "0"));
ddlGroup.SelectedIndex = 0;
DropDownList ddlApp = (DropDownList)e.Row.FindControl("ddlApp");
ddlApp.DataSource = AppDataRepository.GetApp();
ddlApp.DataValueField = "App_Name";
ddlApp.DataTextField = "App_Name";
ddlApp.DataBind();
ddlApp.Items.Insert(0, new ListItem("--Select App--", "0"));
ddlApp.SelectedIndex = 0;
}
}
Try with HeaderTemplate
<asp:TemplateField HeaderText="ID"
<asp:Label ID="lblID" runat="server" Text='<%# Bind("[ID]") %>'></asp:Label>
</ItemTemplate>
<HeaderTemplate>
<asp:DropDownList ID="ddlID" runat="server" Width="150px" AutoPostBack="True"
OnSelectedIndexChanged="ddlID_SelectedIndexChanged" />
</HeaderTemplate>
</asp:TemplateField>
add FooterStyle-HorizontalAlign="Right" to the parent column of the template
Since Internet explorer dropped support for css top:expression - I have had to separate gridview headers into a separate table.
I have a table. In the first row / first cell I put another table containing the table headers.
In the next row / first cell I have a div set to be 20px wider than the table above (to allow for scroll bar on div). The div contains the gridview with no header. In the pre_render of the gridview I set the widths of the columns in both tables.
I spend a bit of time checking the size of the user screen etc and setting widths for the the tables / div (and a height for the div). The result is a table with static headers which are exactly the same width as the gridview below. You could easily do this and add an extra row in the header table to contain the controls that are currently in the footer row of the gridview.
I have three grids - Category grid, Items grid and Sub Items Grid. I have category grid (grdCategories) and for each category there are many items which i bind to child grids (grdItems). For every item there are many sub items which i display in sub child grid (grdSubItems). Now the problem is that page takes too much of time in loading the data. My HTML Code is below:
It takes even minutes to load the data:
ASPX
<asp:GridView ID="grdCategories" runat="server" AutoGenerateColumns="false" DataKeyNames="Category"
CssClass="menu_items" OnRowDataBound="grdCategories_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Panel ID="pnlMealOptionsHeader" runat="server" Width="100%">
<h1>
<a id='<%# Eval("CategoryX")%>'>
<asp:Label ID="lblCategory" runat="server" Text='<%#Eval("Category") %>' Visible="false"></asp:Label>
<asp:Label ID="lblCategoryX" runat="server" Text='<%#Eval("CategoryX") %>'></asp:Label>
</a>
</h1>
</asp:Panel>
<asp:Panel runat="server" ID="pnlMealOptionsBody">
<asp:Label ID="lblCategoryXX" runat="server" CssClass="title_2" Text='<%#Eval("CategoryXX") %>'></asp:Label>
<!--Items in Category -->
<asp:GridView ID="grdItems" runat="server" AutoGenerateColumns="false" CssClass="active-grid"
DataKeyNames="Item" OnRowDataBound="grdItems_RowDataBound" ShowHeader="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblItem" runat="server" Text='<%#Eval("Item") %>' Visible="false"></asp:Label>
<asp:Label ID="lblItemX" CssClass="title" runat="server" Text='<%#Eval("ItemX") %>'></asp:Label>
<asp:Label ID="lblItemXX" CssClass="title" runat="server" Text='<%#Eval("ItemXX") %>' style=" font-size:smaller; font-weight:normal"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:GridView ID="grdSubItems" runat="server" AutoGenerateColumns="false" CssClass=""
DataKeyNames="SubItem" ShowHeader="false" OnRowDataBound="grdSubItems_RowDataBound">
<HeaderStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblItem" runat="server" Text='<%#Eval("Item") %>' Visible="false"></asp:Label>
<asp:Label ID="lblSubItem" runat="server" Text='<%#Eval("SubItem") %>' Visible="false"></asp:Label>
<asp:Label ID="lblNoofOptions" runat="server" Text='<%#Eval("NumofOptions") %>' Visible="false"></asp:Label>
<asp:Label ID="lblSubItemX" CssClass="qty" runat="server" Text='<%#Eval("SubItemX") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPrice" runat="server" CssClass="price" Text='<%#String.Format("£{0}",Eval("SellingCost")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<!--End Items in Category -->
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<table width="900px">
<tr>
<td align="center">
<h1>
No Data Available</h1>
</td>
</tr>
</table>
</EmptyDataTemplate>
</asp:GridView>
Code Behind
Categories Gridview Bind
private void FillCategoriesGrid()
{
DataSet ds = new DataSet();
ShopCategoryMapBL bl = new ShopCategoryMapBL(SessionContext.SystemUser);
bl.FetchForShop(ds, RowId);
grdCategories.DataSource = ds.Tables[0].DefaultView;
grdCategories.DataBind();
}
Items Gridview Bind
protected void grdCategories_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView chkTopings = e.Row.FindControl("grdItems") as GridView;
Label lblCategory = e.Row.FindControl("lblCategory") as Label;
FillItemsGrid(chkTopings, WebHelper.Cast(lblCategory.Text, 0));
}
}
protected void FillItemsGrid(GridView grdItems, int Category)
{
try
{
//int cleanOrder = CargoBag.GetValue("CleanOrder", 0);
DataSet aDataSet = new DataSet();
ItemBL bl = new ItemBL(SessionContext.SystemUser);
bl.FetchForCategory(aDataSet, Category, RowId);
grdItems.DataSource = aDataSet.Tables[0];
grdItems.DataBind();
}
catch (Exception ex) { }
}
Sub Items Gridview Bind
protected void grdItems_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridView grdSubItems = e.Row.FindControl("grdSubItems") as GridView;
Label lblItem = e.Row.FindControl("lblItem") as Label;
FillSubItemsGrid(grdSubItems, WebHelper.Cast(lblItem.Text, 0));
}
}
protected void FillSubItemsGrid(GridView grdSubItems, int Item)
{
try
{
//int cleanOrder = CargoBag.GetValue("CleanOrder", 0);
DataSet aDataSet = new DataSet();
SubItemBL bl = new SubItemBL(SessionContext.SystemUser);
bl.FetchForItem(aDataSet, Item);
grdSubItems.DataSource = aDataSet.Tables[0];
grdSubItems.DataBind();
}
catch (Exception ex) { }
}
You need to provide all of your code before we can provide an accurate answer.
For example:
Where SubItemBL is defined?
Also try to see what line is the exact bottleneck.
Is it
bl.FetchForCategory(aDataSet, Category, RowId);
or
grdSubItems.DataBind();
If above line is the bottleneck, note that Gridview binding to a datasource with large number of data is indeedslow. how large is your data?
I have the following database design:
Employee Table: Username, Name, JobTitle, BadgeNo, IsActive, DivisionCode
Divisions Table: SapCode, DivisionShortcut
And I have a GridView that I am using it to add, delete and update/edit the employees information. This information is employee Username, Name, BadgeNo, JobTitle, IsActive and the DivisionShortcut. IsActive is a flag that indicates if the employee is available or in an assignment. I made it as a checkbox and the column should show two values; Active and Inactive. In the Edit mode, the Checkbox will be displayed. If it is checked, then it means the employee is avaiable, otherwise it is inactive.
I wrote the code and everything works fine, but now I am facing two problems and I don't know how to make them work with my code.
The GridView shows True or False instead of Active and Inactive and
I don't know why.
In the Edit mode, the checkbox will be displayed and the values (Active or Inactive) will be displayed besides to it and it shouldn't be displayed. I just want the checkbox to be displayed.
So how to modify them?
ASP.NET code:
<%-- GridView for User Management Subsystem --%>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Username"
DataSourceID="SqlDataSource1" BorderWidth="1px" BackColor="#DEBA84"
CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510"
BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png"
CancelImageUrl="Images/icons/cancel324.png" />
<asp:TemplateField HeaderText="Division">
<ItemTemplate>
<%# Eval("DivisionShortcut")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
DataTextField="DivisionShortcut" DataValueField="SapCode"
SelectedValue='<%# Bind("DivisionCode")%>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True"
SortExpression="Username" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job Title">
<ItemTemplate>
<%# Eval("JobTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Badge No.">
<ItemTemplate>
<%# Eval("BadgeNo")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<%# Eval("IsActive")%>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
//for updating the (IsActive) column using checkbox inside the GridView
protected void isActive_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow gvrow = (GridViewRow)chkStatus.NamingContainer;
//Get the ID which is the NetworkID of the employee
string username = gvrow.Cells[2].Text;
bool status = chkStatus.Checked;
string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string updateIsActive = "UPDATE Employee SET IsActive = #IsActive WHERE Username = #Username";
SqlCommand cmd = new SqlCommand(updateIsActive, conn);
cmd.Parameters.AddWithValue("#IsActive", status);
cmd.Parameters.AddWithValue("#Username", username);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (SqlException se)
{
throw se;
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
UPDATE:
I update my code as following:
ASP.NET Code:
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Username"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" BorderWidth="1px" BackColor="#DEBA84"
CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510"
BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png"
CancelImageUrl="Images/icons/cancel324.png" />
<asp:TemplateField HeaderText="Division">
<ItemTemplate>
<%# Eval("DivisionShortcut")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
DataTextField="DivisionShortcut" DataValueField="SapCode"
SelectedValue='<%# Bind("DivisionCode")%>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True"
SortExpression="Username" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job Title">
<ItemTemplate>
<%# Eval("JobTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Badge No.">
<ItemTemplate>
<%# Eval("BadgeNo")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive")%>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-Behind:
//For showing Active or Inactive in the IsActive column instead of True or False
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Here we will select the IsActive column and modify its text
Label isActive = new Label();
isActive = (Label)e.Row.FindControl("lblIsActive");
//Now, after getting the reference, we can set its text
isActive.Text = "Active or Inactive";
// First check Checkedbox is check or not, if not make it grey
//if (e.Row.Cells[6].Text == "False")
// GridView1.BackColor = Color.Gray;
}
}
And I am getting the following error and I don't know why:
For question no: 1
You have to add an Row_DataBound Event of your grid view, in which you select the IsActive column and replaced its text by Active and InActive. But before going to code behind make a little change to you aspx code: In your item template instead of direct binding place a label control and bind it as I does in the below code:
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive") %>' ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'/>
</EditItemTemplate>
</asp:TemplateField>
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// here you will select the IsActive column and modify it's text
Label isActive=new Label();
isActive = (Label) e.row.FindControl("lblIsActive");
// after getting the reference set its text
isActive.Text="Active or InActive";
}
}
For question no 2:
Remove the condition form this
Eval("IsActive").ToString().Equals("True") ? " Active " : " Inactive " %>'
and replace it with
Eval("IsActive")
Now check boxes will be displayed.
Updated Answer:
You are receiving an object reference not found error, Please debug your site and check it why you are unable to get the exact reference. I saw you code and it looks that your code is fine.
To prove that my code is working,I created a gridview with a single column
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
// and bind this grid view in the Page_Load of my Page
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("name");
DataRow row = dt.NewRow();
row[0] = "Waqar Janjua";
dt.Rows.Add(row);
GridView1.DataSource = dt;
GridView1.DataBind();
}
// When I view this page in the browser it shows "Waqar Janjua"
// Now to update the columns text, I add the following code and it works.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState != DataControlRowState.Edit)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l = new Label();
l = (Label)e.Row.FindControl("Label1");
l.Text = "waqar";
}
}
}
// When I run this page now, it shows me "Waqar" not "Waqar Janjua" The code works for me.
It is returning "true" or "false" as it is expecting a boolean data type from IsActive. If you want to change that out put, I suspect you need to amend this conditionally on the ItemDataBound event of the grid.
I have a GridView with an anonymous type. I need to check the value in a cell and highlight that cell if a condition is met. The problem is, I always get an empty string when I try to pull data out of the row's cells. I have successfully highlighted all the cells and I have checked in the Visual Studio 2010 debugger and confirmed that the Row has data (the row's DataItem has the values I need). This is happening on a PostBack, I'm not sure if that's a problem or not.
Here is the code and solutions I've tried:
protected void grvValidCourses_RowDataBound(Object sender, GridViewRowEventArgs e) {
if (e.Row.RowType == DataControlRowType.DataRow) {
String str = e.Row.Cells[6].Text.ToString(); // empty string
Label lbl = (Label) grvValidCourses.FindControl("lblEndDate"); // null
DataRowView rowView = (DataRowView)e.Row.DataItem; // exception about casting anonymous type
What's going on here? Why can't I get data from the cells?
Markup for GridView:
<asp:GridView ID="grvValidCourses" runat="server" Width="790px" OnRowCancelingEdit="grvValidCourses_RowCancelingEdit"
OnRowEditing="grvValidCourses_RowEditing" OnRowUpdating="grvValidCourses_RowUpdating" OnRowDeleting="grvValidCourses_RowDeleting"
AutoGenerateColumns="False" OnSelectedIndexChanged="grvValidCourses_SelectedIndexChanged"
OnRowDataBound="grvValidCourses_RowDataBound" >
<Columns>
<asp:CommandField ShowEditButton="True" EditText="Edit" UpdateText="Update |" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="lbnDelete" runat="server" CausesValidation="False" CommandName="Delete"
Text='<%# (Eval("active") == null ? "Delete" : ((Eval("active").ToString() == "0" ? "Restore" : "Delete"))) %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowSelectButton="True" SelectText="Details" />
<asp:TemplateField HeaderText="Training Name" SortExpression="coursename">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("coursename") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("coursename") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ttNo" HeaderText="#" SortExpression="ttNo" ReadOnly="True" />
<asp:TemplateField HeaderText="Course Date" SortExpression="startDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("startdate", "{0:M/d/yyyy}") %>'></asp:TextBox>
<asp:CalendarExtender ID="TextBox3_CalendarExtender" runat="server" Enabled="True"
TargetControlID="TextBox3" Format="M/d/yyyy">
</asp:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("startdate", "{0:M/d/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Expiry Date" SortExpression="endDate">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("enddate", "{0:M/d/yyy}") %>'></asp:TextBox>
<asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" Enabled="True"
TargetControlID="TextBox1" Format="M/d/yyyy">
</asp:CalendarExtender>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblEndDate" runat="server" Text='<%# Bind("enddate", "{0:M/d/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>No valid courses found.</EmptyDataTemplate>
</asp:GridView>
UPDATE: I've been trying all your suggestions, but I get exceptions or nulls or empty strings. I've even re-created the problem in a simpler example and still can't figure it out! I'll keep trying though, and I appreciate any new suggestions.
Part 1 - Missing Text
You are probably getting blank values in the first part due to a need to access a child control:
String str = ((DataBoundLiteralControl)e.Row.Cells[6].Controls[0]).Text;
To see if your cells have any values in debug mode (check text in debug output window):
void grvValidCourses_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Diagnostics.Trace.WriteLine(e.Row.Cells.Count);
foreach (TableCell c in e.Row.Cells)
{
System.Diagnostics.Trace.WriteLine(c.Text);
}
}
}
Part 2 - Missing Control
This is wrong:
Label lbl = (Label) grvValidCourses.FindControl("lblEndDate"); // null
You can't search the gridview for a row's control. You need to search the row.
Label lblProductOptionGrpName = (Label)e.Row.FindControl("lblProductOptionGrpName");
Part 3 - Accessing DataItem
DataBinder.Eval(e.Row.DataItem, "ColumnName")
Finally, I'm not sure what you're doing with your anonymous types, but you may need to check the contents before accessing properties:
if(MyControl.GetType() == typeof(HyperLink))
{
HyperLink TestLink = (HyperLink)MyControl;
TestLink .Visible = false;
}
Okay I finally figured out what is going on! I can only access the bound field through the row (e.g. e.Row.Cells[index].Text). So I used the bound field to get the ID of my item, then found the item in the database, got the date, compared it, and highlighted the row's cells. Not the most efficient way, but it works.
Code from simple sample:
Grid View Front End
<asp:GridView ID="gdv" runat="server" AutoGenerateColumns="True" OnSelectedIndexChanged="gdv_SelectedIndexChanged">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Select" />
<asp:BoundField DataField="id" HeaderText="#" ReadOnly="True" />
<asp:TemplateField HeaderText="CategoryName" >
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" >
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("desc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblSelected" runat="server" Text="No row selected"></asp:Label>
Code Behind Page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
var qry = ctx.Categories
.Select(c => new {
id = c.CategoryID,
name = c.CategoryName,
desc = c.Description,
});
gdv.DataSource = qry;
gdv.DataBind();
}
}
protected void gdv_SelectedIndexChanged(object sender, EventArgs e) {
selectRow();
}
private void selectRow() {
GridViewRow row = gdv.SelectedRow;
String strId = row.Cells[1].Text; // Bound Field column
lblSelected.Text = strId;
// use ID to get object from database...
}
If you can post markup, then it will be possible to figure out your issue.
You are doing this in wrong way,
this DataRowView rowView = (DataRowView)e.Row.DataItem;
should be DataRow rowView = ((DataRowView)e.Row.DataItem).Row;
protected void gridPanne_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
Label label = (Label)e.Row.FindControl("Label4");
lbl.Text += " ** / ** "+label.Text;
}
}