Moonlight
Moonlight

Reputation: 708

How to get selected column-names of Datagridview

i have found several examples/questions about getting row numbers of the selected cells but not many about getting Column names.

i want to check if a column is named: Frequency. i check if the user select 2 rows bofore doing my stuff.

i tried the following approaches:

if (Dat.SelectedColumns[0].ToString() == "Frequency"
    || Dat.SelectedColumns[1].ToString() == "Frequency")

this was not working, my initially thought was that i needed the headernames to check, my next try:

if (Dat.SelectedColumns[0].HeaderText == "Frequency"
   || Dat.SelectedColumns[1].HeaderText == "Frequency")

this is not working, as selectedColumns remains null. (inex out of range exception)

is there a way to get the names of the selected columns/check if the name is "frequency"?

edit:

// get the Column name of the selected data
int Xcor = Dat.CurrentCellAddress.X;
string ColumnName = Dat.Columns[Xcor].Name;

this method is not working im my case, i need to get 2 ColumnNames, not only the current selected

Upvotes: 0

Views: 9600

Answers (1)

V4Vendetta
V4Vendetta

Reputation: 38230

I am not sure of the SelectionMode which you have set for the grid, since you need to look out for specific columns it would be better to go for CellSelect.

In that case you have dataGridView1.SelectedCells and by going through each you would have the RowIndex as well as the ColumnIndex which would help you identify the specific column.

If this is not what you intend please update the question.

Upvotes: 3

Related Questions