c# - 如何加载列表从数据网格视图
问题描述
我有一个gridview,我正在尝试使用网格视图中的一列加载列表,并且我得到一个空引用异常
我试过这个
public static List<string> LoadStringList()
{
List<string> stringList = new List<string>();
if (contactDataGridView.RowCount != 0)
{
for (int i = 0; i < contactDataGridView.Rows.Count; i++)
{
stringList.Add((string)contactDataGridView.Rows[i].Cells[2].Value);
}
}
return stringList;
}
我试过这个
public static List<string> LoadStringList()
{
List<string> stringList = new List<string>();
if (frmPRG299.mainForm.contactDataGridView.RowCount != 0)
{
for (int i = 0; i <frmPRG299.mainForm.contactDataGridView.Rows.Count; i++)
{
stringList.Add((string)frmPRG299.mainForm.contactDataGridView.Rows[i].Cells[2].Value);
}
}
return stringList;
}
进一步解释
我有两种形式frmMain和frmSub,其中gridview在frmMain和一个组合框在frmSub我需要调用函数LoadStringList()
来填充组合框
解决方案
使用允许您引用对象(在本例中为 Control)的方法,并将对该对象的引用传递给该方法。
如果没有硬编码的对象引用,您的方法会更加灵活。
在这里,我将一个DataGridView
控件引用和一个从中提取当前值的单元格编号传递给该方法。
由于Cell.Value
可能是null
,您必须在尝试读取它和/或将其转换为所需类型之前对其进行验证。
List<string> MyList = LoadStringList(this.dataGridView1, 2);
public List<string> LoadStringList(DataGridView dgv, int cell)
{
if ((dgv == null) || (dgv.RowCount == 0)) return null;
List<string> result = dgv.Rows.Cast< DataGridViewRow>()
.Select(r => { return r.Cells[cell].Value != null
? r.Cells[cell].Value.ToString()
: default; })
.ToList();
return result;
}
如果需要更通用的输入类型:
try
{
List<int> MyList = LoadList<int>(this.dataGridView1, 2).ToList();
}
catch (Exception ex)
{
//Handle the exception/Update the UI/Prompt the User
Console.WriteLine(ex.Message);
}
public IEnumerable<T> LoadList<T>(DataGridView dgv, int cell)
{
if ((dgv == null) || (dgv.RowCount == 0)) return null;
IEnumerable<T> result = null;
try
{
result = dgv.Rows.Cast<DataGridViewRow>()
.Select(r => { return r.Cells[cell].Value != null
? (T)Convert.ChangeType(r.Cells[cell].Value, typeof(T))
: default;
})
.ToList();
}
catch (Exception ex) {
//Manage the exception as required
throw ex;
}
return result;
}
推荐阅读
- java - Java 对多个字符串执行相同的操作
- javascript - 浏览器不显示带有画布的图像
- angularjs - 使用 angularjs 材料实现 4 单元格网格布局
- javascript - 通过条件缩小联合类型
- elasticsearch - 如何实时分析大数据?
- html - Twitter的Bootstrap,右/左列边距不均匀
- html - chrome中的全屏视频覆盖链接
- javascript - “传统”网站的每页 Webpack 4 代码拆分
- c - Linux 的内存布局(C 中使用了 malloc(),但不是从预期的地址开始)
- asp.net-core - ASP.Net Core Windows Auth - Cookie 中的缓存声明