简体   繁体   中英

How do I use different Fields in the same column in a DataGridView

I have a, probably unique situation in which I need to use a single column for two different alternating values.

My data has seperate columns for date and time. Not my choice, I have to live with it. Rows are displayed in "pairs" Row 1 and 2 are part of the same functional unit, but they are seperate rows in the database. In the grid, Row 1, column 1 has to use the date column while in row 2 column 1 is the time column. This repeats for eavery even and odd row. See ASCII drawing below.

Is it possible to make a cell hidden on one row but not another, and then make both fields share a common column header?

I'm also open to using other grids if you know of one that makes this functionality easier to accomplish.

-----------------------------------------------------------------
|Date/Time| ......
=================================================================
|1/1/2008 | .......
|10:00pm  | .......
-----------------------------------------------------------------
|1/2/2008 | .......
|7:00pm   | .......
-----------------------------------------------------------------
...
...
...

If you have control over the data feed coming into your system, say a SQL Stored Procedure, what about something like this?

SELECT 
   ROWID AS 'ID'
   , MYDATE + MYTIME AS 'MYDATETIME'
FROM
   MYTABLE

If you don't have control over the data source, I'd recommend using the on Row_Databound event and changing the text of the cell to meet your needs. This may mean you make cell 3 equal to cell 3 + cell 4 and then hide cell 4... But either way, the Row_Databound would probably be a good fit...

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //ASSUMES COLUMN 2 IS DATE
        //AND COLUMN 3 IS TIME
        e.Row.Cells[2].Text = e.Row.Cells[2].Text + " " + e.Row.Cells[3].Text;
        e.Row.Cells[3].Visible = false;
    }
}

I would refactor the database to a more logical format, then proceed.

If you absolutely cannot change the database, I would maybe wrap the GridView and add the custom functionality you need to deal with special case data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM