views:

52

answers:

2

Hi.I have a field in my table with name (Kind) .it's type is int and, i give 0 and 1 values in app.now i want bind my datagridview with this table,and i want to add new columns (with this name:msg) to my datagridview ,that if kind=0 ,msg column (the cell value) will be "Manual", and if kind=1 ,msg column (the cell value) will be "Database" for example. output of datagridview will be like:

      Kind       msg
   ----------------------- 
       0        Manual
       1       Database
       0        Manual

which instruction i should write to get this goal? i mean how can i add a new column to datagridview and how can i set value to each cells? thanks for your attention.

A: 

Make use of Rowdatabound in gridview examples

Example :

productsGridView_RowDataBound Event Handler (C#)
void productsGridView_RowDataBound(object sender, 
  GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        // determine the value of the UnitsInStock field
        int unitsInStock = 
         Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, 
         "UnitsInStock"));
        if (unitsInStock == 0)
            // color the background of the row yellow
            e.Row.BackColor = Color.Yellow;
    }
}
Pranay Rana
+1  A: 

If your data source is a System.Data.DataTable, then you could make use of expression columns.

You'll have to decide whether that is an acceptable solution, and you'll also have to identify a suitable place within your code to add an expression column to your DataTable, but your code would look something like this:

dataTable.Columns.Add("msg", typeof(string), "IIF(Kind = 0, 'Manual', IIF(Kind = 1, 'Database', 'Unknown'))");
Dr. Wily's Apprentice
@Dr. Wily's Apprentice:i write this code but this error occured:"The expression contains undefined function call IFF()".
na.fa
@Dr. Wily's Apprentice:The correct function name is IIf not IFF.thanks...
na.fa
Sorry about that. I've updated the answer.
Dr. Wily's Apprentice