C# 将所有数据从dataGridView传输到文本框
问题是。我有一个餐馆程序,在这个程序中,顾客选择他想吃的东西,数据显示在dataGridView中。例如,6道不同的菜=6行,每行包含名称、金额和价格。毕竟,我需要打印账单,所以我想将所有信息从dataGridView获取到文本框。所有行。我怎么能做到 另外,我搜索了很多,但只有关于如何将CurrentRow数据传输到我找到的文本框的信息C# 将所有数据从dataGridView传输到文本框,c#,datagridview,C#,Datagridview,问题是。我有一个餐馆程序,在这个程序中,顾客选择他想吃的东西,数据显示在dataGridView中。例如,6道不同的菜=6行,每行包含名称、金额和价格。毕竟,我需要打印账单,所以我想将所有信息从dataGridView获取到文本框。所有行。我怎么能做到 另外,我搜索了很多,但只有关于如何将CurrentRow数据传输到我找到的文本框的信息 private void Form4_Load(object sender, EventArgs e) { Form1 f1 = n
private void Form4_Load(object sender, EventArgs e)
{
Form1 f1 = new Form1();
string billinfo = string.Empty;
foreach (DataGridViewRow row in f1.dataGridView1.Rows)
{
billinfo = string.Format("{0}{1} {2} {3}{4}", billinfo, row.Cells["Name"].Value, row.Cells["Amount"].Value, row.Cells["Price"].Value, Environment.NewLine);
}
textBox1.Text = billinfo;
}
只需循环遍历每一行并将列值格式化为字符串,添加
System.Environment.NewLine
,以在文本框中分隔条目
string billInfo = string.Empty;
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
billInfo = string.Format("{0}{1} {2} {3}{4}", billInfo, row.Cells["Name"].Value, row.Cells["Amount"].Value, row.Cells["Price"].Value, Environment.NewLine);
}
this.textBox1.Text = billInfo;
看起来你有多种形式。每个表单都有自己的“上下文”,以跟踪属于每个表单的“控件”
在您的代码中,“Form4_Load”是在启动“Form4”期间触发的事件。然后在这个方法中创建“newform1()”。这是Form1类型的新空表单。但它与您的第一个“Form1”实例没有任何关联。您必须使用已创建的“f1”
修复程序的粗略方法如下(如下所示),但抓取对象的全局实例并使用它并不是一种好的做法。很容易忘记哪些对象是有效的。无论如何,这是我的简单解决方法
enter code here
private void Form4_Load(object sender, EventArgs e)
{
//I am assuming f1 is the name of your original Form1
String f1DataGridViewName = f1.dataGridView1.Name.ToString();
int f1RowCount = f1.RowCount;
string billinfo = string.Empty;
Console.Writeline("Form1 f1 Datagridview name is: {0}
,Form1 f1 DataGridview row count is : {1}"
,f1DataGridViewName, f1RowCount );
foreach (DataGridViewRow row in f1.dataGridView1.Rows)
{
billinfo = string.Format("{0}{1} {2} {3}{4}", billinfo
, row.Cells["Name"].Value
, row.Cells["Amount"].Value
, row.Cells["Price"].Value
, Environment.NewLine);
}
textBox1.Text = billinfo;
}
您希望它以任何方式格式化还是出于任何原因直接挂在文本框中?@horHay我希望它以dataGridView:name quantity price(ex:soup 1$3.2)中的方式格式化。我尝试了您的方法。但我试图从另一个表单获取dataGridView值,但它不起作用,我的代码看起来就是这样。请参阅我编辑的帖子。@user1898760是Form1
中的DataGridView
公共吗?添加列时,您是否将它们命名为名称、金额和价格?如果两个问题都是肯定的,您看到了什么错误/结果?两个问题都是肯定的。我甚至试着写0,1,2来代替列名。我没有得到任何类型的错误,我只是得到没有任何信息的空文本框。@user1898760这让我相信,当您声明Form1
的新实例时,它的构造函数必须注意向DataGridView
添加正确的列,但不负责填充行(因此,没有错误,也没有数据)。如果Form1
已经存在并且通过某个层次链父级Form4
,则Form4
不应声明Form1
的新实例,而应引用原始实例。这是一种可能发生的情况。问题是它没有以任何方式作为父对象,而不是声明新实例。顺便说一下,我试着从Form1
上的文本框到Form4
上的文本框获取数据,效果非常好。我真的不知道现在该怎么做才能从dataGridView获取数据。。。