wolfQueen wolfQueen - 2 months ago 23
C# Question

Gridview must show Text instead of the Value from the database

I have a gridview that gets the data from a database.
Here is the .NET code. Theres a lot of columns, and here the template: Choice is the one im talking about.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AllowPaging="True" CellPadding="4" DataKeyNames="EmpID" ForeColor="#333333" GridLines="None" style="margin-right: 81px" Width="1174px" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Choice" SortExpression="Choice">
<EditItemTemplate>
<asp:DropDownList ID="DropDownChoice" Text='<%# Bind("Choice") %>' runat="server" Width="60px">
<asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblChoice" runat="server" Text='<%# Bind("Choice") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>


Here on the EditItemTemplate, the user may edit the said data on the database. Where I can use a drop down list and show the text as No or Yes but the value that will be saved on the database is still 0 and 1.

<EditItemTemplate>
<asp:DropDownList ID="DropDownChoice" Text='<%# Bind("Choice") %>' runat="server" Width="60px">
<asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>


Im having trouble of showing the text No and Yes on the Gridview once it runs. As you can see here is the ItemTemplate code:

<ItemTemplate>
<asp:Label ID="lblChoice" runat="server" Text='<%# Bind("Choice") %>'></asp:Label>
</ItemTemplate>



Please suggest a way/method to show No/Yes on the ItemTemplate/Gridview section once executed. Thanks (let me know if you might need the C# code to bind data on the gridview)


NOTE:
I have tried the RowDataBound event that was answered in this question.
here is the code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRow dr = ((System.Data.DataRowView)e.Row.DataItem).Row;

if (dr["Choice"].ToString() == "0")
{
((Label)e.Row.FindControl("lblChoice")).Text = "No";
}
else if (dr["Choice"].ToString() == "1")
{
((Label)e.Row.FindControl("lblChoice")).Text = "Yes";
}
}
}


But it doesnt work. am I missing something? Do I have to include something in the tag ?? thanks

Answer

As far as I understood, you can either use Render Property function or row data bound event.

RenderProperty Function

RowDataBound Event

Both answers are from this question

Edit: As you asked how to call the RowDataBound event, it's added to the GridView tag like this:

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"></asp:GridView>