samedi 9 mai 2015

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

First i would like to say that i am REALLY new to WPF.

I am trying to fill a datagrid with data from my MySQL database, by doing queries using radio buttons.I want to have one of my radio buttons set to the default selection, when starting the program. But i get a "Index was out of range. Must be non-negative and less than the size of the collection parameter name:index" when i have my radiobutton set to "IsChecked="True" in my xaml. If i remove the IsChecked and run the program again and manually select the radiobutton, there is no problems. Can anyone tell me what i am doing wrong?

This is not my actual code, it is just the parts of the code needed to get the error i am having.

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://ift.tt/o66D3f"
    xmlns:x="http://ift.tt/mPTqtT"
    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");
    }
}

}

Aucun commentaire:

Enregistrer un commentaire