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

社会主义新天地 提交于 2019-12-31 00:44:39

问题


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 adapter and I'm storing it in a DataSet and a DataGridView will show the contents from the DataSet

In the gridview, for column Xyz, a check_box with/without tick is displayed but I want to display it as a buy/sell as a text instead of checkbox.


回答1:


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.



来源:https://stackoverflow.com/questions/13157891/bit-datatype-to-enum-type-mapping-from-database-to-dataset-in-sql-server-2008

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!