首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用底层bindingsource中的行在datagridview行上执行样式更改?

如何使用底层bindingsource中的行在datagridview行上执行样式更改?
EN

Stack Overflow用户
提问于 2018-12-14 04:08:04
回答 2查看 114关注 0票数 0

我有一个win forms应用程序,允许用户插入或更新SQL表。当用户单击"upload“时,datagridview中的数据将合并到sql表中。我希望datagridview行更改颜色以指示插入或更新。

我不知道如何将datagridview行与bindingsource中的底层行关联起来。请看我的评论“救命!”下面

代码语言:javascript
复制
partial class Form1 : Form
{
    SqlConnection _con;
    BindingSource _bs;
    DataTable _dt;

    public Form1()
    {
        // START 
        InitializeComponent();

        // SQL connection
        _con = new SqlConnection(connString);

        // Data binding
        _bs = new BindingSource();
        _dt = new DataTable();
        dataGridView1.DataSource = _bs;
        _bs.DataSource = _dt;            
    }

    /// <summary>
    /// Converts the datagridview into a datatable
    /// </summary>
    /// <param name="dgv"></param>
    /// <returns></returns>
    private DataTable GetDataTableFromDGV(DataGridView dgv)
    {
        var dt = new DataTable();
        foreach (DataGridViewColumn column in dgv.Columns)
        {
            if (column.Visible)
            {
                dt.Columns.Add(column.Name.ToString());
            }
        }

        object[] cellValues = new object[dgv.Columns.Count];
        foreach (DataGridViewRow row in dgv.Rows)
        {
            for (int i = 0; i < row.Cells.Count; i++)
            {
                cellValues[i] = row.Cells[i].Value;
            }
            if ((string)cellValues[0] != "" && (string)cellValues[1] != "" && cellValues[0] != null && cellValues[1] != null)
                dt.Rows.Add(cellValues);
        }

        return dt;
    }

    private void btnUpload_Click(object sender, EventArgs e)
    {
        //Store errors to output to user at the end
        StringBuilder ts = new StringBuilder();

        _dt = GetDataTableFromDGV(dataGridView1);
        if(_dt.Rows.Count > 0)
        {
            _con.Open();

            foreach (DataRow dr in _dt.Rows)
            {
                using (SqlCommand command = new SqlCommand())
                {
                    int returnVal;

                    command.Connection = _con;
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = "dbo.InsertZebraLocationXRef";

                    SqlParameter param1 = new SqlParameter
                    {
                        ParameterName = "@Horse",
                        Value = dr.Field<String>("Horse"),
                        SqlDbType = SqlDbType.VarChar
                    };
                    SqlParameter param2 = new SqlParameter
                    {
                        ParameterName = "@Zebra",
                        Value = dr.Field<String>("Zebra"),
                        SqlDbType = SqlDbType.VarChar
                    };

                    command.Parameters.Add(param1);
                    command.Parameters.Add(param2);

                    try
                    {
                        returnVal = (int)command.ExecuteScalar(); //this returns 0 for insert, 1 for update
                        MessageBox.Show(returnVal.ToString());
                    }
                    catch (SqlException ex)
                    {
                        if (ex.Number == 2627)
                        {
                            ts.Append("Primary key constraint violated when entering " + dr.Field<string>("Horse") + " " + dr.Field<string>("Zebra") + Environment.NewLine);
                        }
                        if (ex.Number == 515)
                        {
                            ts.Append("Cannot insert null value" + Environment.NewLine);
                        }
                        Debug.WriteLine(ex.ToString());
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.ToString());
                    }

                    // Help! I want to update the DGV row style here based on the returnVal                     
                }
            }

            // Output errors to screen
            if (ts.Length > 0)
            {
                ts.Append(Environment.NewLine + "The other rows were added successfully." + Environment.NewLine + Environment.NewLine + "Press CTRL + C to copy this box to your clipboard. Please email it to the helpdesk.");
                MessageBox.Show(ts.ToString(), "Written by Vic Street", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show("Upload complete", "Upload complete", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            _con.Close();

        }
    }
}

为将来的读者编辑:我通过向datatable添加另一个列"Style“来解决这个问题,并对以下代码进行了更改:

代码语言:javascript
复制
                    if (dr.Field<String>("Style") == "1")
                        dataGridView1.Rows[_dt.Rows.IndexOf(dr)].DefaultCellStyle.BackColor = Color.Red;
                    if (dr.Field<String>("Style") == "0")
                        dataGridView1.Rows[_dt.Rows.IndexOf(dr)].DefaultCellStyle.BackColor = Color.Green;
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-14 05:18:56

尝试使用CellFormatting事件根据行的RowState状态设置行的颜色:

代码语言:javascript
复制
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
  if (e.RowIndex < _dt.Rows.Count) {
    if (_dt.Rows[e.RowIndex].RowState == DataRowState.Added) {
      dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
    } else if (_dt.Rows[e.RowIndex].RowState == DataRowState.Modified) {
      dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Blue;
    }
  }
}
票数 0
EN

Stack Overflow用户

发布于 2018-12-14 04:28:22

如果我没理解错的话,你可以尝试这样做:

代码语言:javascript
复制
DataGridViewCellStyle highlightCellStyle = new DataGridViewCellStyle();
highlightCellStyle.BackColor = Color.Green;
dataGridView1.CurrentRow.DefaultCellStyle = highlightCellStyle;

基于返回样式的颜色应该不是问题,我认为。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53769344

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档