Bit datatype to enum type mapping from database to dataset in SQL Server 2008

后端 未结 1 451
南方客
南方客 2021-01-19 07:19

I have a table which has a column Xyz and it has bit datatype in SQL Server 2008.

I\'m getting the values from the table through data adapt

相关标签:
1条回答
  • 2021-01-19 07:52

    You can handle it in 1 of 2 ways.

    1) Instead of returning the data as a bit, do the casting in your query to have it return Buy/Sell as a string based on the value. This will only really work well if your grid is read-only. If you need to be able to add/edit data, it would get messy to convert your Buy/Sell back to a bit and enforce that the user could only enter buy/sell. You'd probably want to use method 2 if you need to add/edit data.

    e.g. let's say your column name is called BuySell and is of type bit

    SELECT CASE WHEN BuySell = CAST(0 AS BIT) THEN 'Buy' ELSE 'Sell' AS BuySell FROM TableName
    

    2) You will have to turn off "Autogeneratecolumns" on the DataGridView and setup your columns manually. If your grid is read-only, I'd add a text column for your buy/sell column that maps to your bit value. Then in the Cell_Formatting event for the grid, update the value based on the bit. Something like the below:

    private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (dgv.Columns[e.ColumnIndex].Name == "buysell")
        {
            if (e.Value != null)
            {
                if (e.Value.ToString() == "1")
                {
                    e.Value = "Sell";
                }
                else
                {
                    e.Value = "Buy";
                }
            }
            else
            {
                e.Value = "Buy";
            }
        }
    }
    

    If your grid needs to be editable, setup a DataTable that represents your Buy/Sell values with a displaymember and valuemember. Bind that as the datasource for a combobox column. Now loading the data will correctly display Buy/Sell in the combobox and for new rows when you select a value from the drop-down it will populate your underlying datasource with the correct bit value.

    0 讨论(0)
提交回复
热议问题