【问题标题】:C# Having trouble with populating drop down list with multiple different informationsC#在使用多个不同信息填充下拉列表时遇到问题
【发布时间】:2021-12-19 16:42:21
【问题描述】:

我正在构建一个用于订购电话的表单应用程序。我有一个下拉列表,需要有不同商店的地址。地址存储在 MSSQL 数据库中,其中状态、城市、街道和邮政编码是表存储中的不同列。我无法让下拉列表显示州、城市、街道而不是想要的数据,我在下拉列表中选择 System.DataRowView。我尝试只要求城市或州,它可以工作并显示正确的数据。

有没有办法获取所有三个信息(州、城市、街道)或者我应该只更改 sql 表以将这些数据包含在一个列中?

代码如下:

            try
            {
                SqlConnection connection = getConnection();
                connection.Open();
                SqlCommand sc = new SqlCommand("select state,city,street,sotreID from store", connection);
                SqlDataReader reader;
                reader = sc.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Columns.Add("street", typeof(string));
                dt.Columns.Add("storeID", typeof(int));

                dt.Load(reader);
                prodavnicaCombo.ValueMember = "storeID";
                prodavnicaCombo.DisplayMember = "state,city,street"; //the troublsome line is here
                
                prodavnicaCombo.DataSource = dt;
                connection.Close();
            }
            catch (Exception err)
            {
                MessageBox.Show("Exception: " + err.Message);
            }

【问题讨论】:

  • 你说得对,我会改正错字
  • 尝试select state + ',' + city + ',' + street as toDisplay 然后更改prodavnicaCombo.DisplayMember = "toDisplay"; 旁白:您缺少using 块来处理您的Sql 对象
  • 请为您的连接使用using 语句,如果发生异常,您让连接保持打开状态。我也很少发现err.Message 在使用 sql 时很有用,使用err.ToString() 它将有更多的调试信息。
  • 没有区分WinForms、WPF等的标签,请加一个。
  • 我建议你向你的教授how to use using blocks and what they do解释,因为他们似乎不知道

标签: c# sql winforms


【解决方案1】:

ValueMember 和 DisplayMember 属性中只能使用一列。但是您可以使用以下方法,而不是更改数据库,只需在查询中连接您的显示成员列并使用它

 try
            {
                SqlConnection connection = getConnection();
                connection.Open();
                SqlCommand sc = new SqlCommand("select (state + ' ' city + ' ' + street) as displayMember,sotreID from store", connection);
                SqlDataReader reader;
                reader = sc.ExecuteReader();
                DataTable dt = new DataTable();
                dt.Columns.Add("street", typeof(string));
                dt.Columns.Add("storeID", typeof(int));

                dt.Load(reader);
                prodavnicaCombo.ValueMember = "storeID";
                prodavnicaCombo.DisplayMember = "displayMember"; //the troublsome line is here
                
                prodavnicaCombo.DataSource = dt;
                connection.Close();
            }
            catch (Exception err)
            {
                MessageBox.Show("Exception: " + err.Message);
            }

【讨论】:

  • 谢谢你的朋友,我会试试你的解决方案。
猜你喜欢
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 2011-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多