What do I have:
- Filled datagridview
- Selected cells of this grid
What do I want:
- Amount of unique columns of the selected cells
- Names of these columns
What I found:
int selectedColumnsCount = dataGridView3.SelectedColumns.Count;
Somehow this piece of code isn't working in my case.
My question: How can I get the columns name and the amount of columns selected out of a DataGridView
?
This is what I created now:
int selectedCellCount = dataGridView3.GetCellCount(DataGridViewElementStates.Selected);
int selectedcolumncount = dataGridView3.SelectedColumns.Count;
ArrayList arr = new ArrayList();
int j = 0;
if (selectedCellCount > 0)
{
for (int i = 0; i < selectedCellCount; i++)
{
int Xcor2 = int.Parse(dataGridView3.SelectedCells[i].ColumnIndex.ToString());
test = test + dataGridView3.Columns[Xcor2].Name;
arr.Add(dataGridView3.Columns[Xcor2].Name);
}
}
ArrayList arr2 = new ArrayList();
foreach (string str in arr)
{
if (!arr2.Contains(str))
{
arr2.Add(str);
j++;
}
}
This is what I made myself, not that nice but its working to get the count of columns if anyone has a better way of realizing this开发者_如何学运维, feel free to add
You can register for the SelectionChanged
event and process the SelectedCells
. For example
public Form1()
{
InitializeComponent();
dataGridView1.SelectionChanged += new EventHandler(dataGridView1_SelectionChanged);
}
HashSet<int> column_indicies = new HashSet<int>();
HashSet<string> column_names = new HashSet<string>();
int number_of_columns = 0;
void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
column_indicies.Clear();
column_names.Clear();
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
// Set of column indicies
column_indicies.Add(cell.ColumnIndex);
// Set of column names
column_names.Add(dataGridView1.Columns[cell.ColumnIndex].Name);
}
// Number of columns the selection ranges over
number_of_columns = column_indicies.Count;
}
You cannot select columns. Only one columns can be selected at a time! Columns are the same as Rows. Or did you mean to get those columns, which cells are slected?
Ok, this is one of the way of getting column names (you can even use HeaderText property instead of Name):
List<DataGridViewColumn> listOfColumns = new List<DataGridViewColumn>();
foreach (DataGridViewCell cell in dataGridView1.SelectedCells)
{
DataGridViewColumn col = dataGridView1.Columns[cell.ColumnIndex] as DataGridViewColumn;
if (!listOfColumns.Contains(col))
listOfColumns.Add(col);
}
StringBuilder sb =new StringBuilder();
foreach (DataGridViewColumn col in listOfColumns)
sb.AppendLine(col.Name);
MessageBox.Show("Column names of selected cells are:\n" + sb.ToString());
精彩评论