Click here to Skip to main content
15,909,039 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
I'm trying to find a way to prevent my datagridview from selecting the first cell as default cell. Right now I have code that turns the backcolor of the cells in my datagridview to red if negative numbers are in the cells on import. However this won't work properly in my first cell since its already highlighted by default on import. If anyone can find out how to turn the selecting of the cell off I would greatly appreciate it! :)

I know it must be something simple like DataGridView1.CurrentCell.Selected = False
Posted
Updated 31-Jul-13 9:39am
v2

It is just that simple :)

datagridview1.ClearSelection()
 
Share this answer
 
Comments
CAS1224 5-Aug-13 19:04pm    
Just what I was looking for. Thanks so much!
Tiaan Lombard (TiLO) 6-Aug-13 2:10am    
Only a pleasure!
I wrote a test following you're description and all cells colored correctly.
There's more info at http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcell.aspx[^]

C#
public partial class Form1 : Form
    {
        private Random rnd;
        private int nSize = 4;

        public Form1()
        {
            InitializeComponent();
            rnd = new Random();
            for (int c = 0; c < nSize; c++)
            {
                this.dataGridView1.Columns.Add("Col" + c.ToString(), "Col" + c.ToString());
            }
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            this.dataGridView1.Rows.Clear();
            int n = this.dataGridView1.Columns.Count;
            string[] nums;
            for (int r = 0; r < nSize; r++)
            {
                nums = new string[n];
                for (int c = 0; c < n; c++)
                {
                    nums[c] = (rnd.Next(-10, 10)).ToString();
                }
                this.dataGridView1.Rows.Add(nums);
                
            }
            ColorCells();
        }

        private void ColorCells()
        {
            int n = this.dataGridView1.Columns.Count;
            for (int r = 0; r < nSize; r++)
            {
                for (int c = 0; c < n; c++)
                {
                    string val = (string) this.dataGridView1.Rows[r].Cells[c].Value;
                    int v;
                    if(Int32.TryParse(val, out v) == false) continue;

                    if(v<0)
                        this.dataGridView1.Rows[r].Cells[c].Style.BackColor = Color.Red;
                    else
                        this.dataGridView1.Rows[r].Cells[c].Style.BackColor = Color.White;
                }
                
            }
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900