views:

541

answers:

2

I'm binding my gridview's bound columns with datafield using the column name of my datatable. The problem is we have a scenario we need to put in a text where the datafield was int with value 0. I couldn't see any work around. Is there any easy way to do this?

A: 

If this is ASP.Net, you can make this a Template column and do the following:

<ItemTemplate>
   <%# MyConversionFunction(Convert.ToInt32(DataBinder.Eval(Container.DataItem, "IntegerFieldName"))) %>
</ItemTemplate>

protected string MyConversionFunction(int ValueToCheck)
{
   if(ValueToCheck.ToString() == "0")
   {
      return "SomeText";
   }
   else
  {
      return SomeValue.ToString();
  }
}
David Stratton
+2  A: 

If you don't like to use inline code in your aspx pages as David has suggested make a template with a literal control in it and implement the OnDataBinding event:

For example in your grid have the following template for your field:

<asp:TemplateField HeaderText="Your Header Name">
    <ItemTemplate>
        <asp:Literal runat="server" ID="litYourCustomField" OnDataBinding="litYourCustumField_DataBinding"></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

Then you implement the OnDataBinding in your code behind:

protected void litYourCustomField_DataBinding(object sender, System.EventArgs e)
{
    Literal lit = (Literal)(sender);
    int yourInt = Convert.ToInt32(Eval("YourNumber"));
    lit.Text = (yourInt == 1) ? "It's a 1" : "It's something else";
}

I prefer this method to the inline code since it puts no code in your aspx pages. I usually have a #region defined in my .cs file that has all by databinding code. I am pretty sure performance wise they will be pretty much identical except for maybe the overhead of the literal control if you have the viewstate enable. Make sure to turn off viewstate when you don't need it.

Kelsey