简体   繁体   中英

WPF C# Populate data into combobox from seperate class file

I have three files here which populates the data from the database and assign it to the xaml views.

This is my user.cs file which holds the user functions:

public List<User> getUserList()
    {
        var user = new List<User>();
        string query;
        query = "select * from users";
        da = new MySqlDataAdapter(query, db.GetConnection());
        da.Fill(dt);
        reader = db.QueryCommand(query);
        ComboBox cb = new ComboBox();
        while (reader.Read())
        {
            user.Add(new User()
            {
                UserId = reader[0].ToString(),
                UserName = reader[1].ToString(),
                UserCreatedDate = reader[5].ToString(),
                UserEmail = reader[6].ToString(),
                UserFirstName = reader[7].ToString(),
                UserLastName = reader[8].ToString(),
                UserRole = reader[3].ToString()

            });
        }
        reader.Close();

        return user;

    }

This is my viewusers.cs file:

private void btnUpdate_Click(object sender, RoutedEventArgs e)
    {
        TextBox txtFirstName = (TextBox)GetChildren(userDataGrid).First(x => x.Name == "txtFirstName");
        TextBlock txtBlockId = (TextBlock)GetChildren(userDataGrid).First(x => x.Name == "txtBlockId");
        ComboBox cbUserRole = (ComboBox)GetChildren(userDataGrid).First(x => x.Name == "cbUserRole");
        string firstName = txtFirstName.Text;
        string id = txtBlockId.Text;
        string userRole = cbUserRole.SelectedItem.ToString();
    }

This is my viewusers.xaml file:

  <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <Border BorderThickness="0" Background="BlanchedAlmond" Padding="10">
                    <StackPanel Orientation="Horizontal">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontSize="12" Text="User Role: " VerticalAlignment="Center" />
                            <ComboBox x:Name="cbUserRole" FontSize="16" Foreground="MidnightBlue" Text="{Binding UserRole}" VerticalAlignment="Center" />
                        </StackPanel>
                        <StackPanel>
                            <Button x:Name="btnUpdate" Content="Update" VerticalAlignment="Center" HorizontalAlignment="Right" Click="btnUpdate_Click"/>
                        </StackPanel>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>

Now, the problem is I am not able to populate the user roles to the combobox. How can I solve this problem? Since the combobox is not present in the views file, I am not able to locate the combobox from the user class file.

For MVVM Pattern i sent my code. i hope its may work for you.

.xaml view file :

 <Grid Style="{DynamicResource Dropdown_grid}" Grid.Column="0" Grid.Row="1">
                                        <StackPanel Grid.Column="0" HorizontalAlignment="Left" Style="{DynamicResource Dropdown_stakpanel}">
                                            <TextBlock HorizontalAlignment="Left" Name="FeesGroup" TextWrapping="Wrap" FontWeight="Bold" Text="Select Fees Group *" VerticalAlignment="Top"/>
                                            <ComboBox x:Name="drpfeesgroup" MinHeight="30" HorizontalAlignment="Left" Background="Black" SelectedValuePath="Tag" Tag="{Binding id}" MinWidth="200" ItemsSource="{Binding Path=Persons}" SelectedItem="{Binding Path=SPerson}">
                                            </ComboBox>
                                        </StackPanel>
                                    </Grid>

.xaml.cs File Code : Call In Constructor if you want to show in page load event.

 var ds = feesMaster_ViewModel.Dropdown_Feesgroup();
        if (ds.Tables[0].Rows.Count > 0)
        {
            drpfeesgroup.ItemsSource = ds.Tables[0].DefaultView;
            drpfeesgroup.DisplayMemberPath = ds.Tables[0].Columns["name"].ToString();
            drpfeesgroup.SelectedValuePath = ds.Tables[0].Columns["id"].ToString();
        }

feesMaster_ViewModel.ViewModel.cs File : (Create method for bind datagrid)

public DataSet Dropdown_Feesgroup()
    {
        var ds1 = new DataSet();
        using (con = new MySqlConnection(ConfigurationManager.ConnectionStrings["schoolmanagment_connectionString"].ToString()))
        {
            try
            {
                con.Open();
                cmd = new MySqlCommand("select id,name from fee_groups", con);
                da = new MySqlDataAdapter(cmd);
                ds = new DataSet();
                da.Fill(ds, "fee_groups");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    ds1 = ds;
                }

            }
            catch (Exception ex)
            {
                var a = ex.ToString();
                throw;
            }
            finally { con.Close(); }
            return ds;
        }

    }

I Hope, My This Code will help you to solve your problem. I Will Try to my best to give solution of your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM