locked
DataGridView in Windows binding RRS feed

  • Question

  • I need to bind two values of DataSet in DataProperty of DataGridView in WinForms using C#

     

    like for instance the header of the columns id Qty/Unit

    quantity comes from Quantity Column and unit comes From Unit Column of DataSet but while providing the DataProperty name how can i show both the values in onle column of datagrid view.

    Please help asap

    Regards,

    Kuldeep


    Regards Kuldeep Gupta
    Thursday, February 17, 2011 9:06 AM

Answers

  • One way is to add an expression column to your data table before you bind it to the grid:

    private void Form1_Load(object sender, EventArgs e)
        {
          // dummy up a data set
          var qty  = new DataColumn("Qty", typeof(short));
          var unit = new DataColumn("Unit", typeof(float));
          var both = new DataColumn("Qty/Unit", typeof(string), "Qty + ' / ' + Unit");
          var table = new DataTable("Table");
          var data = new DataSet("Data");
          
          table.Columns.Add(qty);
          table.Columns.Add(unit);
          table.Columns.Add(both);
          data.Tables.Add(table);
    
          // and some sample data
          table.Rows.Add(1, 1.99);
          table.Rows.Add(2, 2.99);
          table.Rows.Add(3, 0.99);
    
          // bind the data to the grid
          dgv.DataSource = data.Tables["Table"];
          dgv.Columns["Qty"].Visible = false;
          dgv.Columns["Unit"].Visible = false;
        }
    

    The other way involves adding an empty column to the grid and capture the DataGridView.CellFormatting event to format the cell contents.

        void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
          if (e.ColumnIndex == dgv.Columns["Qty/Unit"].Index)
          {
            /* get values from other two columns and build string here */
            e.Value = "Imagine a formatted value";
            e.FormattingApplied = true;
          }
        }
    
    

    What works best is probably a combination of both to hide the case when the data would be "0 / 0.00"


    This signature unintentionally left blank.
    • Proposed as answer by Shishir DK Wednesday, February 23, 2011 11:17 AM
    • Marked as answer by eryang Thursday, February 24, 2011 10:07 AM
    • Unmarked as answer by silverrock7 Tuesday, March 8, 2011 11:28 AM
    • Marked as answer by silverrock7 Tuesday, March 8, 2011 11:28 AM
    Thursday, February 17, 2011 10:40 PM