C# 获取数据库行中的所有项目

标签 c# mysql wpf

我想创建一个编辑窗口来编辑数据库中的行。

如何读取数据库行中的所有项目?

到目前为止我的代码是:

private void FirmCustomerValues()
    {
        config conf = new config();
        connection = new MySqlConnection(conf.connection_string);
        try
        {
            if (this.OpenConnection() == true)
            {
                MySqlCommand cmd = new MySqlCommand("SELECT * FROM firmenkunden WHERE id='" + firmCustomerID + "'",connection);

                MySqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    foreach (var row in reader)
                    {
                        System.Windows.Controls.TextBox textbox = new TextBox();

                        // Textbox Properties
                        textbox.Width = 159;
                        textbox.Name = "";
                        textbox.Text = reader[1].ToString();

                        textboxWP.Children.Add(textbox);
                    }



                }

            }
        }
        catch (MySqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

但这不起作用。 有谁知道如何解决这个问题吗?

我想我也需要一个for循环。我是 C# 新手,如果答案很简单,我很抱歉。

最佳答案

只需删除 foreach 循环即可。

reader.Read() 迭代返回的行。

您可以使用reader.HasRows()来确定是否有行

还尝试使用 textbox.Text = reader["ColumnName"].ToString(); 因为这更容易阅读。

生成唯一的文本框名称

var textBoxCounter =0;

在 Read() 循环中

textbox.Name = string.Format("txtText{0}", textBoxCounter);
textbox.Text = reader[1].ToString();
textBoxCounter += 1;

希望有帮助。

关于C# 获取数据库行中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42581516/

相关文章:

c# - 强名称签名对此程序集 stdole.dll 无效

mysql - MySQL 中的列计数与值计数不匹配

mysql - 通过 SSH 以错误的顺序将文本粘贴到 Mysql

c# - WPF 组合框 : click outside of popup suppress mouse click

c# - TreeView,覆盖双击鼠标事件 WPF

C# Bitmap To PictureBox 运行不佳

c# - 无法从程序集“mscorlib”加载类型 'System.Reflection.IntrospectionExtensions'

c# - 如何验证 SalesForce Consumer Key 和 Consumer Secret

mysql - 从外国 id 获取最大计数

wpf - ViewModel 是否应该被不同的 View 重用?如果有,什么时候?