[英]Problems with DataGridView in C# Winforms
我在使用DataGridView时遇到问题。
首先,如您所见:
我正在将信息从DataGridView
传输到Info_Goods
数组。 我仔细检查了一下,它完全转移了我需要的所有信息。
但是,当我使用foreach
将Info_Goods
数组的信息写入text.txt
,只会写入第一行的信息。 我创建了一个不同的数组,名称testArray
之前创建了一些元素
例:
string[,] testArray = {{a,b,c}, {d,e,f}};
它完全写入了testArray的信息。 我不知道发生了什么
string Name = "";
Name = tb_Name.Text;
string[,] Info_Goods = new string[50, 50];
int Number = 1;
for (int i = 0; i < dgv_Input.Rows.Count - 1; i++)
{
for (int j = 0; j < dgv_Input.Columns.Count - 1; j++)
{
Info_Goods[i, j] = dgv_Input.Rows[i].Cells[j].Value.ToString();
}
}
////================================ Write File
// string[,] test = { { "a", "b", "c" }, { "d", "e", "f" } }; // it worked
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Number.ToString() + " " + Name + ".txt"))
{
foreach (string s in Info_Goods) // it didn't worked
{
sw.WriteLine(s);
}
}
其次,我想检查DataGridView中的空元素并显示错误通知。
如您所见,我使用的循环与将信息从DataGridView传输到Info_Goods
array时使用的循环相同。
我使用了1个检查变量(1:空元素,0:不空)。 没用
但是,当我只编写IF语句(不使用循环)时,它起作用了。
int check = 0;
for (int a = 0; a < dgv_Input.Rows.Count - 1; a++)
{
for (int b = 0; b < dgv_Input.Columns.Count - 1; b++)
{
if (string.IsNullOrEmpty(dgv_Input.Rows[a].Cells[b].Value as string)) // it didn't work
{
check = 1;
}
}
}
// if (string.IsNullOrEmpty(dgv_Input.Rows[0].Cells[0].Value as string)) // it worked
您应该按如下所示修改循环。 然后它会正常运行,我的朋友。
for (int i = 0; i < dgv_Input.Rows.Count; i++)
{
for (int j = 0; j < dgv_Input.Columns.Count; j++)
{
Info_Goods[i, j] = dgv_Input.Rows[i].Cells[j].Value.ToString();
}
}
对于您的第一个代码,目前尚不清楚为什么要使用[50,50]的字符串数组? DataGridView
dgv_Input
似乎是调整数组大小的更好方法。 还是最好使用列表。 使用数组的方式将为数组中的许多元素创建空值,否则可能会产生溢出。 假设dgv_Input
有4列和5行数据,在将单元格读入代码后,string [50,50]数组如下所示:
[0,0] data0 col1
[0,1] data0 col2
[0,2] data0 col3
[0,3] data0 col4
[0,4] null
[0,5] null
[0,6] null
…….
[0,47] null
[0,48] null
[0,49] null
[1,0] data1 col1
[1,1] data1 col2
[1,2] data1 col3
[1,3] data1 col4
[1,4] null
[1,5] null
[1,6] null
显然,这浪费了很多空间,并且保证了空值/字符串。 当您尝试将此数组写入文件时,应使用以下命令检查这些空值:
If (s != null)…
您可能需要重新考虑如何从DataGridView
存储字符串...我猜每行有1个字符串,可能将它们存储在List
因为您可能不知道这里有多少个字符串。
对于您的第二个问题,我想问题在于以下代码行:
string.IsNullOrEmpty(dgv_Input.Rows[a].Cells[b].Value as string)
我认为这并没有返回您的期望。 首先, dgv_Input.Rows[a].Cells[b].Value
可能为null。 我知道该行似乎在询问是否为空值IsNullOrEmpty
的STRING。 如果DataGridView单元格中的值是数字,则上面的行也将返回true。 换句话说,上面的行似乎没有按预期方式工作。 在下面,我细分了代码以检查哪些值是null或哪些值是空字符串。 这似乎按预期工作
for (int a = 0; a < dataGridView1.Rows.Count -1 ; a++) {
for (int b = 0; b < dataGridView1.Columns.Count; b++) {
if (dataGridView1.Rows[a].Cells[b].Value != null) {
if (dataGridView1.Rows[a].Cells[b].Value.ToString() != "") {
textBox1.Text += dataGridView1.Rows[a].Cells[b].Value.ToString() + ",";
} else {
// MessageBox.Show("String is empty: ");
}
} else {
//MessageBox.Show("DGV Cell Value is null: ");
}
}
textBox1.Text += Environment.NewLine;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.