我有什么:
我想要什么:
我找到了什么:
int selectedColumnsCount = dataGridView3.SelectedColumns.Count;
不知何故,这段代码在我的情况下不起作用。
我的问题:如何从DataGridView
中获取列名称和列数?
这就是我现在创建的:
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++;
}
}
这就是我自己创造的,不是那么好,但如果有人有更好的方法来实现这一点,它会努力获得列数,随意添加
答案 0 :(得分:1)
您可以注册SelectionChanged
事件并处理SelectedCells
。例如
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;
}
答案 1 :(得分:0)
您无法选择列。一次只能选择一列! 列与行相同。 或者你的意思是获得那些列,哪些单元被选中?
答案 2 :(得分:0)
好的,这是获取列名的方法之一(您甚至可以使用HeaderText属性而不是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());