【问题标题】:Select row from DataGridView and place it in a textbox从 DataGridView 中选择行并将其放在文本框中
【发布时间】:2016-11-08 22:17:58
【问题描述】:

我有一个 Windows 窗体应用程序,它有一个 datagridview 来显示一个满是饭菜的菜单。

我希望能够允许用户选择座位号,然后选择一行,一旦选择了该行,该行中的所有信息将被放入下面的可用文本框中,然后将在新的文本框中提交xml 文件,标题为 order.xml

到目前为止,我已对 xml 部分的保存进行了排序,但我似乎无法完成 datagridview 任务。

将数据保存在 order.xml 文件中的代码。

XDocument doc = XDocument.Load("order.xml");
        XElement root = new XElement("MenuInfo");
        root.Add(new XElement("Data1", dataGridView.DataSource));
        root.Add(new XElement("Data2", _seat));
        root.Add(new XElement("Data3", buttonTable1.Text));
        root.Add(new XElement("Data4", lbPrice.Text));
        doc.Element("Menu").Add(root);
        doc.Save("order.xml");

        MessageBox.Show("The order has been placed.");

【问题讨论】:

  • root.Add(new XElement("Data1", dataGridView.DataSource)); 你从这条线上得到(期望得到)什么??? - 您可能应该编写一个从 DGV 或 DataTable 行中提取 List 或/和 string[] 的函数。尝试一下,遇到任何问题都回来
  • @TaW 从那个代码我只得到这个插入 Mealseat1Table 1Price 不输出完整的Meal名称,我不确定你的功能部分是什么意思。
  • 什么是datagridview任务?你到底想做什么?
  • @FadiBanna DataGridView 正在显示一个名为 menu.xml 的 xml 文件。我试图让用户选择一行,一旦它被选中,它应该显示在底部的文本框中,其中包含该行的所有信息。这有意义吗?
  • 好吧,我认为您应该考虑编辑您的帖子,这样这一点就很清楚了,您发布的代码与您遇到的问题无关,您应该将您尝试获取选定行的代码发布到文本框,您的问题与 XML 无关,请编辑帖子以便我们为您提供帮助。

标签: c# xml winforms datagridview


【解决方案1】:

您可以对 RowEnter-Event 做出反应,该事件在用户输入一行时触发。然后执行以下操作:

private void dataGridView1_RowEnter(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
        {
            var yourGrid = sender as DataGridView;

            if (yourGrid != null)
            {
                var row = yourGrid.Rows[e.RowIndex].DataBoundItem as DataRowView;

                if (row != null)
                {
                    //Here you have access to the actual row.
                    //So simply get the string foreach column you need
                    string myStringForTextEdit = Convert.ToString(row["MealID"]) + Convert.ToString(row["Food"]) +
                                                 Convert.ToString(row["Price"]) + Convert.ToString(row["Time"]) +
                                                 Convert.ToString(row["Quantity"]);

                    myTextEdit.Text = myStringForTextEdit;
                }
            }
        }

这个简单的例子使用 RowEnter-Event 获取当前行并根据所有行值构建一个字符串。

我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2016-06-25
    • 2021-12-18
    • 2018-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多