Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binding datagrid for Wpf to a DB

I am trying bind a DataGrid for WPF to a table in MS SQL Database.

1) First I created a App.config file as followsrrr

    <connectionStrings> 
      <add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress; 
       User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
    <connectionStrings/>

2) Secondly, I added a datagrid to my Form with a name grdEventLog

      <Grid>
        <DataGrid Name="grdEventLog"/>
      </Grid>

3) then I added this code to MainWindow.xaml.cs file as follows:

     using System.Data;
     using System.Data.SqlClient;
     using System.Web;

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

    private void FillDataGrid()
    {
        string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
        string CmdString = string.Empty;
        using (SqlConnection con = new SqlConnection(ConString))
        {
            CmdString = "SELECT Server,Date,Typ,Msg FROM EventLog";
            SqlCommand cmd = new SqlCommand(CmdString, con);
            SqlDataAdapter sda = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable("EventLog");
            sda.Fill(dt);
            grdEventLog.ItemsSource = dt.DefaultView;
        }
    }

After typing all these entries, I have the error at ConfigurationManager stating "The name does not exist in the current context"

I am trying to add reference cfgmgr32.dll to overcome this error. But it is not being accepted. Can anyone suggest to over come this error ?!

Alternative suggestion for approaching databinding in WPF is also welcome.

like image 711
Indhi Avatar asked Nov 12 '22 16:11

Indhi


1 Answers

The problem is not in databinding itself. Seems, there is a typo either in config file, or in key used in ConnectionStrings[]. It would be useful if you post entire error with stacktrace here. P.S. There is a typo in your config file. It should be not

<connectionStrings> 
      <add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress; 
       User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
    <connectionStrings/>

but

<connectionStrings> 
      <add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress; 
       User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
    </connectionStrings>

See the last line.

like image 116
Oleg Avatar answered Nov 15 '22 06:11

Oleg