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

标签 c# mysql wpf radio-button

首先我想说我对 WPF 真的很陌生。

我试图通过使用单选按钮进行查询,用我的 MySQL 数据库中的数据填充数据网格。我希望在启动程序时将我的单选按钮之一设置为默认选择。但是当我在 xaml 中将单选按钮设置为“IsChecked=”True”时,我收到“索引超出范围。必须为非负且小于集合参数名称的大小:索引”。如果我删除检查并再次运行程序并手动选择单选按钮,没有问题。 谁能告诉我我做错了什么?

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

<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,因此当您尝试获取column[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);
    }
}

您可以在运行时添加列,并绑定(bind)到数据表。

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>

关于c# - wpf 单选按钮已选中 "Index was out of range. Must be non-negative and less than the size of the collection.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30139437/

相关文章:

c# - 如何使用鼠标滚轮在 WPF 中水平滚动?

c# - NHibernate ISession.save(newTransientEntity) 是否只会返回生成的 Id,但不会更新实体的 Id 属性?

c# - 将 double 日期和时间值转换为另一个时区?

mysql - 从多个表中选择不同的电子邮件

php - 如何在 Laravel 5 中使用 orderBy Desc 获得平均值

MySQL AUTO_INCRMENT 计数器出现一些问题

wpf - 在WPF中,如何在DataGrid上显示AdornerLayer

c# - 如何解决使用主成分分析引发的 OutOfMemoryException

c# - Cross Thread错误处理形式与Timer

c# - RenderTargetBitmap图像质量低的问题