【问题标题】:C#: Connection fails to fill control elements from DataTableC#:连接无法从 DataTable 填充控制元素
【发布时间】:2017-05-20 10:26:19
【问题描述】:

我正在建立一个 SqlServer 数据库连接,以便从表中检索数据并将它们作为输入提供给文本框和组合框。

尽管我没有收到任何异常或错误消息,但结果不是预期的,即使所有数据都返回并存储到表中,两个组合框的行为也不如预期。 此外,还有两个提到控件后面的齿轮被放置在一个图片框中,所有这些都一起“坐”在一个面板上!

这是我的代码:

            try
            {
                using (SqlConnection con = new SqlConnection("Data Source=(local);Initial Catalog=SmartCity;Integrated Security=True"))
                {

                    DataTable db = new DataTable();
                    SqlDataAdapter sda = new SqlDataAdapter("SELECT card_type,card_n
                    umber,exp_month,exp_year,cvv FROM CreditCards WHERE user_id='" + ApplicationState.CurrentUser.userid.ToString() + "'", con);
                        sda.Fill(db);

                    //MessageBox Prints the missing data perfectly though!
                    MessageBox.Show("Cart Type:" + db.Rows[0][0].ToString() 
                    + "\nExpiration Month:" + db.Rows[0][2].ToString()); 

                    txtcardholername.Text = ApplicationState.CurrentUser.name + " " + ApplicationState.CurrentUser.surname;
                    cboxcardtype.Text = db.Rows[0][0].ToString();
                    txtcardnumber.Text = db.Rows[0][1].ToString();
                    cboxmonth.Text = db.Rows[0][2].ToString();
                    cboxexpyear.Text = db.Rows[0][3].ToString();
                    txtcvv.Text = db.Rows[0][4].ToString();
                }

            }
            catch (Exception)
            {
                MessageBox.Show("Something went wrong!");
            }

【问题讨论】:

  • 其他控件是否填充数据库中的数据,而只有组合框不填充?
  • 是的控制年份被初始化为 [2016,2017,2018....] 正在完美加载!

标签: c# .net sql-server datatable database-connection


【解决方案1】:

Solution by the original asker:

这个小细节就是问题所在:

当我创建月份组合框时,我添加了以下值:

因此数据库返回 -6- 作为月份 NOT -06- 不是 一开始就包含在组合框的项目中。

然后我改变了如下图所示的值。

瞧:

【讨论】:

    【解决方案2】:

    您不会通过设置它的 Text 属性来填充组合框。要正确填充 ComboBox,您必须向其中添加项目:

    comboBox1.Items.Add(db.Rows[0][0].ToString());
    

    然后你必须选择它,你会没事的。

    comboBox1.SelectedItem = comboBox1.Items.Cast<KeyValuePair<string,string>>().First(item=> item.Value == db.Rows[0][0].ToString());
    

    【讨论】:

    • 这不是问题,问题非常微妙我添加了解决方案,看看它很有趣!
    猜你喜欢
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-30
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多