1
Answer

Display Sql data in Wpf gridview

dilip rayar

dilip rayar

11y
1.1k
1
Hello, 

I'm new to WPF and trying some hands on with wpf.
I'm trying to publish all my table data on the wpf datagrid on form load.

Here is what I had learnt from internet and tried to implement.

I had written my connection string in App.config file.

<connectionStrings>
<add connectionString="Data source = Dilip; user id = (local); Intital Catalogue =True;" name="AppCs"/>
</connectionStrings>


This is my Main window
    <Grid>
        <DataGrid Name="Prices"></DataGrid>
    </Grid>

Under the code behind.

 public MainWindow()
        {
            InitializeComponent();
            
            MessageBox.Show("I came till here");

            FillDataGrid(); 
        }
        private void FillDataGrid()
        {
            string UsingCs = ConfigurationManager.ConnectionStrings["AppCs"].ConnectionString;

            SqlConnection _Conn = new SqlConnection(UsingCs);
            _Conn.Open();
            string qry = string.Empty;
            qry = "SELECT * FROM prices";
            SqlCommand cmd = new SqlCommand(qry);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("price");
            sda.Fill(dt);
            Prices.ItemsSource = dt.DefaultView;


        }
This is the very basic code written to disaply 4 rowed table data on grid view.


On execution the message box, is being displayed but the following error is shown.

TargetInvocationException was unhandled.

Exception was thrown by the target of an invocation.


Trubleshooting tips:
.....
InnerException: Use the "new" keyword to create an object instance.
InnerException: Check to determine if object is null before calling the method.

unfortunately, I had no idea, where to check and what to replace the null :(

I had eliminated the app.config,  written directly but still I don't see the result.

Please help me to solve this.


Thanks in advance.
Dilip.







Answers (1)