Click here to Skip to main content
15,896,320 members

How to add a DataGrid Dynamically using CodeBehind

MohammadIqbal asked:

Open original thread
C#
private void button2_Click(object sender, RoutedEventArgs e)
       {

           connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Project/Book.accdb";
           connection = new OleDbConnection(connectionstring);
           sql = "Select*from Authors";

           try
           {
               connection.Open();
               oledbAdapter = new OleDbDataAdapter(sql, connection);
               oledbAdapter.Fill(dt);

               // dataGrid1.DataContext = dt;

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

           DataGrid dg2 = new DataGrid();
           dg2.Height = 200;
           dg2.Width = 200;
           dg2.AutoGenerateColumns = true;
           dg2.AlternatingRowBackground = Brushes.Black;
           dg2.Background = Brushes.Red;
           dg2.BorderBrush = Brushes.Pink;
           dg2.HorizontalGridLinesBrush = Brushes.Black;
           dg2.DataContext = dt;
           stackPanel1.Children.Add(dg2);

       }


it is expected that the code should display the DataGrid with its underlying Data. but it is not happening.
it gives only a Red back ground. no data at all .No Grid lines also. I am missing something very seriously. please i request somebody help

Regards

Iqbal
NB: I am just started learning
Tags: C# (C# 4.0), WPF, DataGrid

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900