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"/>
Related
I have a gridview with three columns admin id, admin name and checkbox, and there is a single button below the gridview,
I want to get the value of admin name column and display it in a label when I check the checkbox and then click the button,
I tried doing this and its working fine but I can get one value only for example if I checked two checkbox and then clicked the button it get only the last value, and I want to get them all.
<asp:GridView ID="GridView1" CssClass="datatable" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="10"
AllowSorting="True" EnableViewState="false" width="863px" DataSourceID="SqlDataSource1" >
<Columns >
<asp:TemplateField HeaderText="req_id" >
<ItemTemplate >
<asp:Label ID="label_id" runat="server" Text='<%# Eval("admin_id") %>' ></asp:Label>
</ItemTemplate>
<ItemStyle Width="20px" />
<HeaderStyle Width="30px" />
<FooterStyle Width="20px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="admin_number">
<ItemTemplate >
<asp:Label ID="label_name" runat="server" Text='<%# Eval("admin_name") %>' ></asp:Label>
</ItemTemplate>
<ItemStyle Width="20px" />
<HeaderStyle Width="60px" />
<FooterStyle Width="60px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="privileges" >
<ItemTemplate>
<asp:CheckBox ID="CheckBox_privileges" runat="server" Checked='<%# Convert.ToInt32(Eval("prev_1")) == 1 ? true : false %>' />
</ItemTemplate>
<ItemStyle Width="90px" />
<HeaderStyle Width="90px" />
<FooterStyle Width="90px" />
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void btn_save(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox chkRow = (row.Cells[2].FindControl("CheckBox_privileges") as CheckBox);
if (chkRow.Checked)
{
string name= (row.Cells[1].FindControl("label_name") as Label).Text;
Label4.Text = name;
}
}
}
}
In this line you are overriding the text:
Label4.Text = name;
To add all the text you should do something like this:
Label4.Text = name + Label4.Text;
I am extracting data from database in gridview, where I have given a link button "Edit" for editing the data of that row. However while editing , one of the columns(YEAR) of my gridview becomes a dropdown list. While fetching the data from database, the Column "Year" consists of label and in edit mode it gets changed to dropdownlist. Moreover I added a condition to make the link buttons appear/disappear based on the value of the Label "Year". When I edit the particular row it throws an error because as soon as edit command is called it converts the column into dropdownlist however the row_databound searches for label. It shows "Object not set to an instance....." PLease help
Aspx
<asp:GridView ID="gv1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataSourceID="SqlDataSource2" OnRowDataBound="gv1_RowDataBound" OnRowUpdating="gv1_RowUpdating" DataKeyNames="tid" CssClass="auto-style1" Width="694px">
<Columns>
<asp:TemplateField HeaderText="Sr No">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="tid" SortExpression="tid" Visible="false">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("tid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title" SortExpression="title">
<EditItemTemplate>
<asp:TextBox ID="txtTitle1" runat="server" Text='<%# Bind("title") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Bind("title") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Category" SortExpression="category">
<ItemTemplate>
<asp:Label ID="lblCategory" runat="server" Text='<%# Bind("category") %>'></asp:Label></ItemTemplate>
<EditItemTemplate>
<asp:RadioButtonList ID="rbtnlist" runat="server"><asp:ListItem Text="Soft Skills"></asp:ListItem><asp:ListItem Text="Technical Skills"></asp:ListItem></asp:RadioButtonList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Announced at" SortExpression="dt">
<ItemTemplate>
<asp:Label ID="lblDt" runat="server" Text='<%# Bind("dt", "{0:dd/MMM/yyyy HH:mm tt}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Year" SortExpression="year">
<EditItemTemplate>
<asp:DropDownList ID="ddlyr" runat="server"></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblyr" runat="server" Text='<%# Bind("year") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Id" SortExpression="userid">
<ItemTemplate>
<asp:Label ID="lblUid" runat="server" Text='<%# Bind("userid") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="btndel" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete" OnClientClick="return isConfirm()" Visible="false"></asp:LinkButton>
<%--<asp:LinkButton ID="btnmail" runat="server" CausesValidation="False" OnClientClick="return isConfirm()" Text="Send Mail" Visible="false"></asp:LinkButton>--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="btnupdte" runat="server" CausesValidation="True" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="btncncl" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="btnedit" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="btnmail" runat="server" CausesValidation="False" OnClientClick="return isConfirm()" Text="Send Mail" Visible="false"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
<PagerStyle ForeColor="#003399" HorizontalAlign="Left" BackColor="#99CCCC" />
<RowStyle BackColor="White" ForeColor="#003399" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<SortedAscendingCellStyle BackColor="#EDF6F6" />
<SortedAscendingHeaderStyle BackColor="#0D4AC4" />
<SortedDescendingCellStyle BackColor="#D6DFDF" />
<SortedDescendingHeaderStyle BackColor="#002876" />
</asp:GridView>
c#
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbly = (Label)e.Row.FindControl("lblyr");
if (lbly.Text == DateTime.Now.Year.ToString() || lbly.Text == ((DateTime.Now.Year)-1).ToString())
{
LinkButton btedt = (LinkButton)e.Row.FindControl("btnedit");
LinkButton btdel = (LinkButton)e.Row.FindControl("btndel");
LinkButton btsm = (LinkButton)e.Row.FindControl("btnmail");
btdel.Visible = true;
btedt.Visible = true;
btsm.Visible = true;
}
if ((e.Row.RowState & DataControlRowState.Edit) > 0) {
RadioButtonList rbtnlist = (RadioButtonList)e.Row.FindControl("rbtnlist");
DropDownList ddlist = (DropDownList)e.Row.FindControl("ddlyr");
for (int i = (DateTime.Now.Year); i >= ((DateTime.Now.Year)-1) ; i--)
{
ddlist.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlist.DataBind();
rbtnlist.DataBind();
}
}
}
I am assuming that you are binding your grid with a DataTable with colum name "Year". Try below code where dt refers to your Datatable:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int rowno = e.Row.DataItemIndex;
//Suppose dt is DataTable to which you are binding your grid
//and year is the column name within this datatable
string year = Convert.ToString(dt.Rows[e.Row.DataItemIndex]["year"]);
if (year == DateTime.Now.Year.ToString() || year == ((DateTime.Now.Year) - 1).ToString())
{
LinkButton btedt = (LinkButton)e.Row.FindControl("btnedit");
LinkButton btdel = (LinkButton)e.Row.FindControl("btndel");
LinkButton btsm = (LinkButton)e.Row.FindControl("btnmail");
btdel.Visible = true;
btedt.Visible = true;
btsm.Visible = true;
}
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
RadioButtonList rbtnlist = (RadioButtonList)e.Row.FindControl("rbtnlist");
DropDownList ddlist = (DropDownList)e.Row.FindControl("ddlyr");
for (int i = (DateTime.Now.Year); i >= ((DateTime.Now.Year) - 1); i--)
{
ddlist.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
ddlist.DataBind();
rbtnlist.DataBind();
}
}
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.
}
}
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