Annisha
Annisha

Reputation: 65

Replace data while update in datagrid view using c#

enter image description here

Above image 0's and 1's from the database while showing the value in data grid view 1 is replaced by high and 0 is replace by low I have no idea about this help me to solve this

            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select dataa from new";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();

Upvotes: 2

Views: 560

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

You can handle the case using different solutions, including:

  • Using DataGridViewComboBoxColumn (→ Preferred if you need editing)
  • Using CellFormatting (→ Preferred if you don't need editing)
  • Changing Query to Return Formatted data (→ Useful for read-only data)

Option 1 - Using DataGridViewComboBoxColumn

Add DataGridViewComboBoxColumn:

var c = new DataGridViewComboBoxColumn();
c.DataPropertyName = "Column1"; //Name of your data column
c.HeaderText = "Column1";       //Header text of your data column
c.DataSource = new[] {
    new { Key = 0, Name = "Low" },
    new { Key = 1, Name = "High" } }.ToList();
c.ValueMember = "Key";
c.DisplayMember = "Name";
c.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;  
//You can try other styles as well as setting `ReadOnly` to true
dataGridView1.Columns.Add(c);

Option 2 - Using CellFormatting

Another option would be using CellFormatting event:

dataGridView1.CellFormatting += (obj, args) =>
{
    try
    {
        var value = Convert.ToInt32(args.Value);
        if (value == 0)
            args.Value = "Low";
        if (value == 1)
            args.Value = "High";
        return;
    }
    catch (Exception) { }
    args.Value = "Unknown";
};

Option 3 - Change Query

You can change your query to get formatted data, for example using CASE:

SELECT CASE [YourColumn] WHEN 1 THEN 'High' WHEN 2 THEN 'Low' END AS Column1
FROM [YourTable]

Example output

For all above codes, you can load data from database or just for test use the following test data:*

var dt = new DataTable();
dt.Columns.Add("Column1", typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(0);
dt.Rows.Add(0);
dt.Rows.Add(1);

And make sure you set data source:

dataGridView1.DataSource = dt;

enter image description here

Upvotes: 4

Related Questions