Combobox无法准确获取数据库值

时间:2014-01-03 10:50:22

标签: c# mysql wpf combobox

我正在尝试将Windows窗体应用程序迁移到wpf并且我已经碰壁了。

使用组合框时,SelectedIndexChanged事件已被SelectionChanged替换为wpf等效项。

我的应用程序连接到MySQL数据库,在那里获取所有信息。 我的特定组合框由数据库表中的字段填充。 这个想法是; 选择组合框项目,其他文本框应显示同一行的相应值。 相反,这就是发生的事情。

Example

背后的代码:

    private void Domain_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        // Set connection parameters
        string sqlcon = "datasource = localhost; port = 3306; username = root; password = localhost";
        // Set query to excecute
        string query_fetch = "select * from mail.smtp where domain = '" + this.Domain.Text + "';";
        // declaratons
        MySqlConnection con = new MySqlConnection(sqlcon);
        MySqlCommand cmd_fetch = new MySqlCommand(query_fetch, con);
        MySqlDataReader rdr;

        // Excecution of command
        try
        {
            con.Open();
            rdr = cmd_fetch.ExecuteReader();

            while (rdr.Read())
            {
                // Declarations
                string sdomainid = rdr.GetInt32("domainid").ToString();
                string ssmtp = rdr.GetString("smtp");
                string sport = rdr.GetString("port");
                string ssecurity = rdr.GetString("security");

                // Bindings
                Domain_ID.Text = sdomainid;
                SMTP.Text = ssmtp;
                port.Text = sport;
                security.Text = ssecurity;
            }
            con.Close();

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

xaml:

    <ComboBox x:Name="Domain" SelectedValue="-1" Margin="186,132,0,0" Height="18" VerticalAlignment="Top" HorizontalAlignment="Left" Width="211" FontSize="11" SelectionChanged="Domain_SelectionChanged" TabIndex="4">

它的工作方式与wWinForms中的SelectedIndexChanged事件相同。我似乎无法找到一种方法来在wpf中正确地进行转换。 任何帮助深表感谢。 (请忽略“stmp”拼写错误)

3 个答案:

答案 0 :(得分:1)

我不确定这是否会有所帮助,因为每个人都在向您展示问题的代码,但根据我的经验,如果您使用数据集,则可以非常轻松地解决此问题。如果使用数据源选项卡,则可以使用它来创建要使用的所有表的数据集。然后在数据集中找到该表,并将要使用的属性拖放到组合框中。如果做得不对,应该没有问题。

答案 1 :(得分:0)

我会检查你的XAML绑定控件。检查 UpdateSourceTrigger 的设置,以确保事件向下流向事件处理程序。

<ListView x:Name="RolesListView"
   ItemsSource="{Binding Path=RoleOptionListMember, 
                         ValidatesOnDataErrors=True, 
                         UpdateSourceTrigger=PropertyChanged}"
   SelectionMode="Single"
   ScrollViewer.VerticalScrollBarVisibility="Auto"
   Focusable="True">

答案 2 :(得分:0)

如果正确地从数据库填充ComboBox,则不需要任何SelectionChanged事件。您可以将ComboBox的选定项目的字段绑定到文本框,如下所示:

<ComboBox x:Name="DomainCB" ItemsSource="{Binding}" />

文字框:

<TextBox Text="{Binding Path=SelectedItem.domainid, ElementName=DomainCB}" />
<TextBox Text="{Binding Path=SelectedItem.smtp, ElementName=DomainCB}" />
<TextBox Text="{Binding Path=SelectedItem.port, ElementName=DomainCB}" />
<TextBox Text="{Binding Path=SelectedItem.security, ElementName=DomainCB}" />