wpf 单选按钮 IsChecked "Index was out of range. Must be non-negative and less than the size of the collection."

wpf radiobutton IsChecked "Index was out of range. Must be non-negative and less than the size of the collection."

首先我想说我是 WPF 的新手。

我正在尝试用我的 MySQL 数据库中的数据填充数据网格,方法是使用单选按钮进行查询 buttons.I 希望将我的单选按钮之一设置为默认值 select离子,启动程序时。但是当我在 xaml 中将我的单选按钮设置为 "IsChecked="True 时,我得到一个 "Index was out of range. Must be non-negative and less than the size of the collection parameter name:index"。如果我再次删除 IsChecked 和 运行 程序并手动 select 单选按钮,没有问题。 谁能告诉我我做错了什么?

这不是我的实际代码,它只是获取我遇到的错误所需的部分代码。

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <DataGrid x:Name="DataGridSpil" Margin="0,30,17,19" CanUserAddRows="false" AutoGenerateColumns="True" ColumnWidth="auto"/>
    <RadioButton Content="Alle" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked"/>
</Grid>

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void RadioButton_Checked(object sender, RoutedEventArgs e)
    {

        try
        {
            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandText = "select titel, genre, release_year, console, ownedby, loaned from spil";
            cmd.Connection = DatabaseConnection.GetDefaultConnection();

            MySqlDataAdapter MyAdapter = new MySqlDataAdapter();

            MyAdapter.SelectCommand = cmd;

            DataTable dTable = new DataTable("spil");

            MyAdapter.Fill(dTable);

            DataGridSpil.ItemsSource = dTable.DefaultView;
            DataGridSpil.Columns[0].Header = "Titel";
            DataGridSpil.Columns[1].Header = "Genre";
            DataGridSpil.Columns[2].Header = "Udgivelsesår";
            DataGridSpil.Columns[3].Header = "Konsol";
            DataGridSpil.Columns[4].Header = "Ejer";
            DataGridSpil.Columns[5].Header = "Lånestatus";
        }

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

public class DatabaseConnection
{
    private static MySqlConnection GetConnection(string host, string user, string pwd, string db)
    {
        string conStr = String.Format("server={0};uid={1};pwd={2};database={3}", host, user, pwd, db);
        var con = new MySqlConnection();
        con.ConnectionString = conStr;
        con.Open();
        return con;
    }

    public static MySqlConnection GetDefaultConnection()
    {
        return GetConnection("127.0.0.1", "root", "root", "WaddaYaGot");
    }
}

}

这意味着您正在访问集合中不存在的位置或索引。如果你调试你的代码,你会发现你 Datagrid.Columns.Count = 0,因此当你试图获取列 [0] 时,你会得到一个异常。

作为解决方案,试试这个;

private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
    try
    {
        MySqlCommand cmd = new MySqlCommand();
        cmd.CommandText = "select titel, genre, release_year, console, ownedby, loaned from spil";
        cmd.Connection = DatabaseConnection.GetDefaultConnection();

        MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
        MyAdapter.SelectCommand = cmd;

        DataTable dTable = new DataTable("spil");

        MyAdapter.Fill(dTable);

        DataGridSpil.ItemsSource = dTable.DefaultView;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

您可以在运行时添加列,并绑定到 DataTable。

xaml

<DataGrid
  Name="DataGridSpil"
  AutoGenerateColumns="False"
  ItemsSource="{Binding}">
</DataGrid>

xaml.cs

if (dTable != null) // table is a DataTable
{
  foreach (DataColumn col in dTable.Columns)
  {
    dataGrid.Columns.Add(
      new DataGridTextColumn
      {
        Header = col.ColumnName,
        Binding = new Binding(string.Format("[{0}]", col.ColumnName))
      });
  }

  DataGridSpil.DataContext = table;
}

另一种方法,如果您知道您的列名,则将它们设置在您的 xaml

<DataGrid Name="DataGridSpil" AutoGenerateColumns="False">
                        <DataGrid.Columns>
                                <DataGridTextColumn Header="Titel" Binding="{Binding Titel}" />
                                <DataGridTextColumn Header="Genre" Binding="{Binding Genre}" />

                                .....

                                .....
                        </DataGrid.Columns>

</DataGrid>