views:

3006

answers:

4

I have a DataGridView that I'm binding to a DataTable. The DataTable is a all numeric values. There is a requirement that every n rows in the DataGridView has text in it, rather than the numeric values (to visually separate sections for the user). I am happy to put this text data in the DataTable or in the DataGridView after binding, but I can't see a way to put this text data in either as the column formats for both require numeric data - I get a "can't put a string in a decimal" error for both. Any ideas how I change the format of a particular row or cell in either the DataTable or DataGridView?

A: 
JMD
So you don't think my requirement can be met with the standard DataGridView?
Handleman
Well, I hesitate to say that because there are people here with more experience modifying WinForms control behaviour than me. I'm frankly surprised no one else has piped up.
JMD
A: 

Does this solve your problem?

// Set the data source.
dataGridView1.DataSource = dataTable1;

// Create a new text box column.
DataGridViewColumn c1 = new DataGridViewTextBoxColumn();
const string C1_COL_NAME = "Custom1";
c1.Name = C1_COL_NAME;

// Insert the new column where needed.
dataGridView1.Columns.Insert(1, c1);

// Text can then be placed in the rows of the new column.
dataGridView1.Rows[0].Cells[C1_COL_NAME].Value = "Some text...";

The original data table bindings should still exist.

DanLomas
+2  A: 

You can provide a handler for the DataGridView's CellFormatting event, such as:

    public partial class Form1 : Form
    {
        DataGridViewCellStyle _myStyle = new DataGridViewCellStyle();

        public Form1()
        {
            InitializeComponent();

            _myStyle.BackColor = Color.Pink;
            // We could also provide a custom format string here 
            // with the _myStyle.Format property
        }

        private void dataGridView1_CellFormatting(object sender, 
            DataGridViewCellFormattingEventArgs e)
        {
            // Every five rows I want my custom format instead 
            // of the default
            if (e.RowIndex % 5 == 0)
            {
                e.CellStyle = _myStyle;
                e.FormattingApplied = true;
            }
        }

        ...

For assistance on creating your own styles, refer to the DataGridView.CellFormatting Event topic in the online help.

Dave R.
A: 

I have a datagrid which displays data with unlimited rows which frequanty changes 5 times in a milisecond, and during that time m comparing the old values with new values and also setting color of a perticular cell, its works properly but the problem is that it uses more cpu usage upto 99%. If anybody have any idea regarding this problem then pls reply me on my email id - [email protected]. Thank you in advance.

dinesh
I think you should ask this as your own question, rather than an answer to this question. Use the "ask a question" button at the top right of the page.
Handleman