datagrid :Index out of range

May 31, 2009 at 3:10 AM
Edited May 31, 2009 at 3:15 AM

using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.Linq;

namespace EM

{
     public partial class  Detail : Page
    {
         public  Detail()
        {    

        InitializeComponent();

         Refresh_DataGrid();     //It will give a give a message like"Index out of range",
        }

        private void Refresh_Click(object sender, RoutedEventArgs e)
        {
            Refresh_DataGrid();  //it works ok
        }

private void Refresh_DataGrid()
        {
            try
            {
                using (DBDataContext DBdc = new DBDataContext())
                {
                    DetailDataGrid.ItemsSource = DBdc.Details.ToList();
                   
                    MessageBox .Show ( DetailDataGrid.Columns.Count().ToString ());
                    DetailDataGrid.Columns[0].Header = "ID";
                    DetailDataGrid.Columns[1].Header = "Name";
                    DetailDataGrid.Columns[2].Header = "Birthday";
                    DetailDataGrid.Columns[3].Header = "Gender";
                    DetailDataGrid.Columns[4].Header = "Email";
                    DetailDataGrid.Columns[5].Header = "Address";
                    DetailDataGrid.Columns[6].Header = "Phone Number";
                    DetailDataGrid.Columns[7].Header = "Degree";
                    DetailDataGrid.Columns[8].Header = "Cake";
                    DetailDataGrid.Columns[9].Header = "Tea";
                    DetailDataGrid.Columns[10].Header = "Picture";
                    DetailDataGrid.Columns[11].Header = "Time";
                    DetailDataGrid.Columns[12].Header = "Comment";
                    DetailDataGrid.Columns[13].Header = "Department";

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

        }

}

 

the first   "Refresh_DataGrid();" will give a message like"Index out of range",but if I excute "Refresh_DataGrid();" from a button click event ,it works ok  ,it looks like when the program initializing ,it can't get the total number  of  DataGrid columns.

how can I slove this probolem?