I am using ASP.NET GridView on ASPX page:
<asp:GridView ID="GrdLimitAndUtilization" runat="server" AutoGenerateColumns="False" GridLines="None"
Width="99%" meta:resourcekey="GrdAccountListResource1" OnRowDataBound="GrdLimitAndUtilization_RowDataBound"
ShowHeader="True" rowstyle-cssclass="rowHover" ClientIDMode="Static" CssClass="gridView">
<Columns>
<asp:TemplateField HeaderText="Excess" meta:resourcekey="Excess">
<HeaderStyle HorizontalAlign="Left" Width="120px" CssClass="gridheader" />
<HeaderTemplate> <asp:Label ID="col5a" Text="Excess" runat="server"></asp:Label></HeaderTemplate>
<ItemTemplate>
<asp:HyperLink ID="lnkExcess" runat="server" value='' Text='<%# Bind("Excess") %>'
meta:resourcekey="HyperLink1Resource1"></asp:HyperLink>
<asp:Label ID="Excess_Currency" runat="server" Text='<%# Bind("Currency") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="120px" HorizontalAlign="Left" CssClass="customerProductItemTemp gridviewLeftMargin" />
</asp:TemplateField>
</Columns>
</asp:GridView>
I know I can access GridView column by following code:
GrdLimitAndUtilization.Rows[0].Cells[0].ForeColor = System.Drawing.Color.Green;
BUT, How can I access value/text of only HyperLink control with ID="lnkExcess"??
Thanks.
You can use RowDataBound event like this:-
protected void GrdLimitAndUtilization_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink lnkExcess = (HyperLink)e.Row.FindControl("lnkExcess");
//Access hyperlink's properties here.
}
}
Related
I have a custom GridView in asp.net Page. In PageLoad data will be bound to the grid.
protected void Page_Load(Object sender, EventArgs e)
{
InitDisplayMode(sender);
}
private void InitDisplayMode(Object sender)
{
pnlDetails.Visible = SafetyKeyId != -1;
if (!Page.IsPostBack)
{
BindValues();
}
// some other stuff
}
private void BindValues()
{
MyStrongTypedDataTable tbl = new BusinessObject.GetData();
dataGrid.DataSource = tbl;
dataGrid.DataBind();
}
Grid View Makrup
<asp:GridView ID="dataGrid" runat="server" AutoGenerateColumns="False" OnRowCreated="OnRowCreated"
AllowSorting="true" BorderWidth="0" CellPadding="2" CssClass="subitem w100p"
AllowPaging="true" PageSize="25" RowStyle-Wrap="false" HeaderStyle-Wrap="false"
OnPageIndexChanging="PageGrid" OnRowDataBound="dataGrid_RowDataBound" PagerSettings-Mode="Numeric"
PagerSettings-Position="Bottom" OnSorting="SortGrid" OnRowDeleting="RowDeleting">
<RowStyle CssClass="itemRowStyle"/>
<AlternatingRowStyle CssClass="alternatingItemRowStyle"/>
<HeaderStyle CssClass="headerRowStyle"/>
<Columns>
<asp:TemplateField ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle">
<ItemTemplate>
<asp:HyperLink ID="lnkDetail" runat="server" meta:resourcekey="lnkDetail" ImageUrl='<%# "~/App_Themes/" + Page.Theme + "/icons/16/icon_file.png" %>'
NavigateUrl="~/BrandMgmt/BrandMgmtPublicKey.aspx?"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle">
<ItemTemplate>
<asp:HyperLink ID="lnkEdit" runat="server" meta:resourcekey="lnkEdit" ImageUrl='<%# "~/App_Themes/" + Page.Theme + "/icons/16/icon_edit.png" %>'
NavigateUrl="~/BrandMgmt/BrandMgmtPublicKey.aspx?"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle">
<ItemTemplate>
<asp:ImageButton ID="cmdDelete" Width="16" Height="16" runat="server" ImageUrl='<%# "~/App_Themes/" + Page.Theme + "/icons/16/icon_delete.png" %>'
CommandName="Delete" CommandArgument='<%# Eval("SafetyKeyId") %>' OnCommand="OnDelete"/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyOwnerIdentifier" HeaderText="KeyOwnerIdentifier" meta:resourcekey="ColumnKeyOwnerIdentifier"
ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle" SortExpression="KeyOwnerIdentifier"/>
<asp:BoundField DataField="SafetyKeyName" HeaderText="SafetyKeyName" meta:resourcekey="ColumnSafetyKeyName"
ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle" SortExpression="SafetyKeyName"/>
<asp:BoundField DataField="SafetyKeyTypeId" HeaderText="SafetyKeyTypeId" meta:resourcekey="ColumnSafetyKeyTypeId"
ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle" SortExpression="SafetyKeyTypeId"/>
<asp:BoundField DataField="KeyIndex" HeaderText="KeyIndex" meta:resourcekey="ColumnKeyIndex"
ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle" SortExpression="KeyIndex"/>
<asp:BoundField DataField="FromDate" HeaderText="FromDate" meta:resourcekey="ColumnFromDate"
ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle" SortExpression="FromDate"/>
<asp:BoundField DataField="ToDate" HeaderText="ToDate" meta:resourcekey="ColumnToDate"
ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle" SortExpression="ToDate"/>
<asp:TemplateField ItemStyle-CssClass="itemFieldStyle" HeaderStyle-CssClass="headerFieldStyle"
meta:resourcekey="ColumnPublicKey" SortExpression="PublicKey">
<ItemTemplate>
<div style="max-width: 200px; overflow-y: scroll;">
<asp:Label runat="server" Text='<%# Eval("PublicKey") %>'/>
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Grid hat 3 ImageButtons for detail view, editing and deleting per row. DetaliView Button adds additional Table with data to the Page. Editing makes this Table editable. If the grid is sorted and any of those buttons is beeing clicked, Page loads and any sorting is lost.
How can I maintain the sort setting in PostBack after clicking any of those buttons?
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 gridview populated with elements extracted from a table in the database. Each row contains 2 textboxes and 1 drop down list. The drop down list is filled when the page is loaded.
My issue is: when I edit the row, select another item from the drop down list and then click on update button, nothing changes. The drop down list still returns to its default value, neither the modiefied values are updated in the db (delete doesn't work etc). I can't understand the reason. Please help me.
My Gridview:
<asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView_OnRowDataBound" OnRowUpdating="GridView_OnRowUpdating"
DataKeyNames="id" DataSourceID="DataSource" ><AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowCancelButton="True" />
<asp:TemplateField HeaderText="currentCity" SortExpression="currentCity" ItemStyle- HorizontalAlign="Center" Visible="false">
<ItemTemplate>
<asp:Label runat="server" ID="lblcurrentCity" Text='<%# Bind("CodiceContrattoRisorsa") %>' Visible="false" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="id" SortExpression="id" ItemStyle-HorizontalAlign="Center" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txtId" Text='<%# Bind("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="name" SortExpression="name" ItemStyle- HorizontalAlign="Center" >
<ItemTemplate>
<asp:TextBox runat="server" ID="txtName" Text='<%# Bind("name") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="city" SortExpression="city" ItemStyle- HorizontalAlign="Center">
<EditItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server" Enabled="false" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor="#EFF3FB" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<asp:EntityDataSource ID="DataSource"
runat="server" ContextTypeName="Context"
EntitySetName="users" EntityTypeFilter="user"
EnableDelete="True" EnableUpdate="True" />
Loading page....
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
MyGridView.DataBind();
}
protected void GridViewCausali_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// initialize ddl in gridview
DropDownList ddl = (DropDownList)e.Row.FindControl("ddlCity");
List<city> cities = new List<city>();
cities = GetFromDB();
ddl.DataSource = cities;
ddl.DataBind();
ddl.Items.FindByValue((e.Row.FindControl("lblcurrentCity") as
Label).Text).Selected = true;
}
}
protected void GridView_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddl = (DropDownList)MyGridView.Rows[e.RowIndex].FindControl("ddlCity");
string test = ddl.SelectedValue;
Label lbl = (Label)MyGridView.Rows[e.RowIndex].FindControl("lblcurrentCity");
lbl.Text = ddl.SelectedValue;
ddl.Items.FindByValue((MyGridView.Rows[e.RowIndex].FindControl("lblcurrentCity") as Label).Text).Selected = true;
}
I suggest you to add DefaultContainerName property, add stringconnection
<asp:EntityDataSource ID="DataSource" runat="server"
ConnectionString="name=..."
DefaultContainerName="..."
EntitySetName="users"
EnableDelete="True" EnableInsert="True" EnableUpdate="True"/>
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 am trying to get a gridview to populate text from the database call to my Label as shown
The Results have been tested and are returning the correct names
protected void Page_Load(object sender, EventArgs e)
{
DataTable t = DBProductLink.ListWithOptions(ProductId, LinkType, null);
TestList.DataSource = t ;
TestList.DataBind();
}
The labels are created in the Gridview like this:
<asp:GridView ID="TestList" runat="server" OnRowDataBound="testDataBound" AutoGenerateColumns="false" DataKeyNames="Id">
<Columns>
<asp:TemplateField HeaderText="Sizes">
<asp:ItemTemplate>
<asp:Label ID="sizeLabel" runat="server" Text='<%# Eval("size") %>' />
</asp:ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I then tried to loop through the gridview and access the label using the ondatarowbound, however in this it is null.
protected void testDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
Label sizeLabel = e.Row.FindControl("sizeLabel") as Label;
sizeLabel.Text = "test";
}
I am using the exact same set up with 2 drop boxes and 2 labels on another gridview with a different name on the same page which is not having this problem. Anyone got an idea on this?
The other Gridview is as follows:
<asp:GridView ID="SearchList" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id" OnRowDataBound="SearchList_RowDataBound"
OnRowCommand="SearchList_RowCommand" Width="100%" PageSize="20" >
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:TemplateField HeaderText="Price" SortExpression="Price">
<ItemTemplate>
<robo:MoneyLabel ID="MoneyLabel2" runat="server"
Value='<%# Eval("Price") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:Label ID="typeLabel" runat="server" Text='<%# Eval("Type") %>' />
<asp:HiddenField ID="productId" runat="server" Value='<%# Eval("Id") %>' />
<asp:HiddenField ID="isFabric" runat="server" Value='<%# Eval("IsFabric") %>' />
<asp:HiddenField ID="isOldWizard" runat="server" Value='<%# Eval("IsOldWizard") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options/Color/Size">
<ItemTemplate>
<asp:LinkButton runat="server" ID="GetOptions" Text="Get Options" CausesValidation="false" CommandName="Options" />
<asp:Label ID="OptionLabel" Visible="false" runat="server" Text="Option: " />
<asp:DropDownList ID="ProductOptions" runat="server" Visible="false" />
<asp:Label ID="ColorLabel" Visible="false" runat="server" Text="Color: " />
<asp:DropDownList ID="RibbonColors" runat="server" Visible="false" AutoPostBack="true" />
<asp:Label ID="SizeLabel" Visible="false" runat="server" Text="Size: " />
<asp:DropDownList ID="RibbonSizes" runat="server" Visible="false" AutoPostBack="true" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Add">
<ItemStyle Width="60px" />
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" Text="Add" CommandName="Add" CommandArgument='<%# Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs is
protected void SearchList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
int productId = (int)SearchList.DataKeys[e.Row.RowIndex].Value;
LinkButton GetOptions = e.Row.FindControl("GetOptions") as LinkButton;
DropDownList RibbonColors = e.Row.FindControl("RibbonColors") as DropDownList;
DropDownList RibbonSizes = e.Row.FindControl("RibbonSizes") as DropDownList;
DropDownList ProductOptions = e.Row.FindControl("ProductOptions") as DropDownList;
Label typeLabel = e.Row.FindControl("typeLabel") as Label;
HiddenField isFabric = e.Row.FindControl("isFabric") as HiddenField;
HiddenField isOldWizard = e.Row.FindControl("isOldWizard") as HiddenField;
ProductType typeValue = DBConvert.ToEnum<ProductType>(typeLabel.Text);
bool isFabricValue = Convert.ToBoolean(isFabric.Value.ToString());
bool isOldWizardValue = Convert.ToBoolean(isOldWizard.Value.ToString());
}
I just found the problem
Your markup is wrong it was tricky... I admit it
This tag: <asp:ItemTemplate> should be <ItemTemplate>
Change this:
<asp:TemplateField HeaderText="Sizes">
<asp:ItemTemplate>
<asp:Label ID="sizeLabel" runat="server" Text='<%# Eval("size") %>' />
</asp:ItemTemplate>
</asp:TemplateField>
Into
<asp:TemplateField HeaderText="Sizes">
<ItemTemplate>
<asp:Label ID="sizeLabel" runat="server" Text='<%# Eval("size") %>' />
</ItemTemplate>
</asp:TemplateField>
This should raise an exception... but instead, the ItemTemplate was completely ignored