ASP.NET - how to bind data to gridview in wpf

Asked By srikar
19-Sep-11 05:08 AM
how to bind data to gridview in wpf
  James H replied to srikar
19-Sep-11 05:20 AM

When you use Dependency Properties, the Setters will not be called by bindings, instead they change the value directly (using SetValue or something similar).

Try adding a PropertyChangedCallback, and set a breakpoint in there to see if the value is changed from the GridView.

public static readonly DependencyProperty BoolProperty =
  DependencyProperty.Register("Bool", typeof(bool), typeof(TestRow), new UIPropertyMetadata(false, OnBoolChanged));
private static void OnBoolChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
  //this method will be called everytime Bool changes value
}
  Suchit shah replied to srikar
19-Sep-11 05:24 AM

Creating the Gridview

First of all create a new project, type project C# NET Framework 3.0: Window Application (WPF).

Now add a ListView (not a ListBox), from "All Controls" section in toolbox, and change the Name to "DataList". You will have code like:

<Window x:Class="sample1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="sample1" Height="320" Width="500"
    >
    <Grid>
    <ListView Margin="0,0,0,50" Name="DataList" />
  </Grid>
</Window>

Take a look at the Window.g.cs code. If it is added, the internal DataList will be ok, if not add the next line:

internal System.Windows.Controls.ListView DataList;

You don't need to initialize it because it exists in the XAML section. Run the project to be sure all is working.

XML Databinding

Here I explain in the code explanation how to bind from XML using only XAML (static version) and then from XML with XAML and C# (my favourite way) because it is easier to change the source at runtime.

I will use in this section the next one called "data.xml" file:

 <Customers>
  <Customer>
 <Code>1234</Code>
 <Name>EPI</Name>
 <Country>Sesame Street</Country>
  </Customer>
  <Customer>
 <Code>3234</Code>
 <Name>Paul</Name>
 <Country>United Kingdom</Country>
  </Customer>
 <Customer>
 <Code>3344</Code>
 <Name>Juan</Name>
 <Country>Spain</Country>
  </Customer>
 <Customer>
 <Code>4321</Code>
 <Name>Dodo</Name>
 <Country>Mars</Country>
  </Customer>
</Customers>

Remember XML and .NET 2.0

To bind XML data to a DataGridView in .NET 2.0, you have to add the following code:

string file = "data.xml";
DataSet ds = new DataSet("Table");
ds.ReadXml(file);
dG1.DataSource = ds.Tables[0].DefaultView;

You will now have a fast way to show data:

Screenshot - DC_1.png

XML Binding Using Only XAML

In this case, first you have to create a new Window.Resource:

<Window.Resources>
    <XmlDataProvider x:Key="CustomersDS" Source="C:\data.xml"/>
</Window.Resources>

and now we have to change the listview to have a gridview aspect:

<ListView Margin="0,0,0,50" ItemTemplate="{DynamicResource CustomerTemplate}" 
 ItemsSource="{Binding Source={StaticResource CustomersDS}, XPath=/Customers/Customer}">
      <ListView.View>
        <GridView>
          <GridViewColumn Header="Code" DisplayMemberBinding="{Binding XPath=Code}"/>
          <GridViewColumn Header="Name" DisplayMemberBinding="{Binding XPath=Name}"/>
          <GridViewColumn Header="Country" 
		DisplayMemberBinding="{Binding XPath=Country}"/>
        </GridView>
      </ListView.View>
</ListView>

With this method, you will have a static XML binding using only XAML:

Screenshot - DC_2.png

XML Binding Using XAML and C#

Generate the "data.xml" shown before, and (that's the way I like code), create the method OnLoad. To do that, add the "Loaded" event to the XAML <window> tag:

<Window x:Class="WindowsApplication7.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    ...
    Loaded="OnLoad"
>

And in the window1.xaml.cs, add the namespace using System.Data; and the method:

public void OnLoad(Object o, EventArgs e)
{
            string file = @"c:\data.xml";
            DataSet ds = new DataSet("Table");
            ds.ReadXml(file);
            List1.DataContext = ds.Tables[0].DefaultView;
}

Now you have to assign the link between "Table" and "BindingPath" in the XAML with the following code:

<Grid x:Name="LayoutRoot">
    <ListView Name="List1" Margin="35,34,212,123" 
	ItemTemplate="{DynamicResource CustomerTemplate}" 
	ItemsSource="{Binding Path=Table}">
      <ListView.View>
        <GridView>
          <GridViewColumn Header="Code" DisplayMemberBinding="{Binding Path=Code}"/>
          <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=Name}"/>
          <GridViewColumn Header="Country" DisplayMemberBinding="{Binding Path=Country}"/>
        </GridView>
      </ListView.View>
    </ListView>
</Grid>

To understand better the link between XAML and C#, take a look at this diagram:

Screenshot - DC_3.png

Loaded calls OnLoad that fills the table and paints on gridview. I like this method because you can easily change the datasource.

SQL Server Binding

Create a new database call "Customers" and create inside the table "customers" with this structure:

Screenshot - DC_4.png

We add example data in the table:

Screenshot - DC_5.png

Remember that the user must have a role to access this database and activate datareader and datawriter:

Screenshot - DC_6.png

Now add the namespace: using System.Data.SqlClient; and the modify the previous OnLoad method to have:

public void OnLoad(Object o, EventArgs e)
{
    string s_command = "SELECT Code,Name,Country FROM customers";
    SqlConnection connection = new SqlConnection();
    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand command = new SqlCommand();
    command.CommandText = s_command;
    adapter.SelectCommand = command;
    connection.ConnectionString = "Data Source=192.168.10.9,1433;
	Initial Catalog=Customers;Network Library=DBMSSOCN;
	User ID=temporalguest;Password='';";
    command.Connection = connection;
    DataSet ds = new DataSet();
    adapter.Fill(ds,"Table");
    List1.DataContext = ds.Tables[0].DefaultView;
    connection.Close();
} 

NOTE: The SQL queries are not case sensitive, the XAML are CASE SENSITIVE so, the name of the columns have to be the same as the name of DisplayMemberBinding.

Access DataBinding

Open Access and create a new database called "customers.mdb" and add inside the table "customers" like the previous section.

Add the namespace using System.Data.OleDb; and simply modify the OnLoad method to the next:

public void OnLoad(Object o, EventArgs e)
{
   string s_command = "SELECT Code,Name,Country FROM customers";
   OleDbConnection connection = new OleDbConnection();
   OleDbDataAdapter adapter = new OleDbDataAdapter();
   OleDbCommand command = new OleDbCommand();
   command.CommandText = s_command;
   adapter.SelectCommand = command;
   connection.ConnectionString = 
	@"Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\customers.mdb";
   connection.Open();
   command.Connection = connection;
   DataSet ds = new DataSet();
   adapter.Fill(ds);
   List1.DataContext = ds.Tables[0].DefaultView;
   connection.Close();
}

Screenshot - DC_7.png

Taking care that we have correctly installed MySQLServer, simply add the namespace using MySql.Data.MySqlClient and change the OnLoad method to:

public void OnLoad(Object o, EventArgs e)
{
  string s_command = "SELECT Code,Name,Country FROM customers";
  MySqlConnection connection = new MySqlConnection();
  MySqlCommand command = new MySqlCommand();
  MySqlDataAdapter adapter = new MySqlDataAdapter();
  command.CommandText = s_command;
  adapter.SelectCommand = command;
  connection.ConnectionString = "Server=192.168.10.9;
	Database=Customers;User Id=temporalguest;Password=111111;";
  command.Connection = connection;
  DataSet ds = new DataSet();
  adapter.Fill(ds, "Table");
  List1.DataContext = ds.Tables[0].DefaultView;
  connection.Close();
}

Customizing the GridView

In this article, I show how to customize the main aspects of the gridview. This is a strange control in WPF because it is not accessible from Blend in design time, so here I explain how to customize it in XAML code.

Customize the Header

If you want to customize the header of every column, add the following code in the Listview tag:

<GridView ColumnHeaderTemplate="{StaticResource BlueHeader}">

In case you want to customize per column, add the following code:

<GridViewColumn Header="Code" DisplayMemberBinding="{Binding Path=Code}" 
	HeaderTemplate="{StaticResource BlueHeader}" />

Now simply add the resource in the <Window> tag:

<Window.Resources>
    <DataTemplate x:Key="BlueHeader">
      <StackPanel Orientation="Horizontal" Margin="-5,-5,-5,-5" Width="120">
        <StackPanel.Background>
          <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="#FF223B84" Offset="1"/>
            <GradientStop Color="#FF57A0F4" Offset="0.5"/>
            <GradientStop Color="#FF4B94EC" Offset="0.5"/>
          </LinearGradientBrush>
        </StackPanel.Background>
        <TextBlock Margin="10,10,10,10" Text="{Binding}" 
		VerticalAlignment="Center"  Foreground="White"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

Now we will have a gridview like:

Screenshot - DC_9.png

Customize the Background

That's too easy, you can do it in Blend if you want. The code you need to add in the <ListView> tag is:

<ListView.Background>
        <LinearGradientBrush EndPoint="0.939,0.919" StartPoint="0.061,0.081">
          <GradientStop Color="#FFFFE07E" Offset="0"/>
          <GradientStop Color="#FFFFFAEA" Offset="1"/>
        </LinearGradientBrush>
</ListView.Background>

And then we will have:

Screenshot - DC_10.png

Customize the Rows

First let's change the typical style of the rows. To do that, simply add the next XAML code in the <ListView> tag:

<ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}"  >
          <Setter Property="Height" Value="24" />
          <Setter Property="Background" Value="#5EF4E057" />
          <Setter Property="Foreground" Value="#FF4B94EC"/>
        </Style>
</ListView.ItemContainerStyle>

Now add XAML code to change when the mouse is over. To do that, add an XAML style trigger, with the typical mouse over code you will have:

<ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}"  >
          <Setter Property="Height" Value="24" />
          <Setter Property="Background" Value="#5EF4E057" />
          <Setter Property="Foreground" Value="#FF4B94EC"/>
          
          <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="true">
              <Setter Property="Foreground" Value="DarkBlue" />
              <Setter Property="Background">
                <Setter.Value>
                  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FFFFC704" Offset="0.986"/>
                    <GradientStop Color="#FFF4E057" Offset="0.5"/>
                    <GradientStop Color="#FFF4E057" Offset="0.51"/>
                  </LinearGradientBrush>
                </Setter.Value>
              </Setter>
            </Trigger>
            
          </Style.Triggers>
        </Style>
</ListView.ItemContainerStyle>

And finally, you will have a well styled gridview that was really hardcoded in previous versions of .NET:

Screenshot - DC_12.png

  Reena Jain replied to srikar
19-Sep-11 05:30 AM
hi..

here is the solution check this out..

WINDOWS.XAML

<Window x:Class="IssueAddinOutlook.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"
  Title="Issue List" Height="424" Width="696">
 
<Grid>
  <Grid.ColumnDefinitions>
  <ColumnDefinition Width="102*" />
  <ColumnDefinition Width="590*" />
  </Grid.ColumnDefinitions>
  <Label Height="41" Margin="172,0,265,0" Name="label1" VerticalAlignment="Top" FontSize="22" Grid.Column="1">Issue List</Label>
 
  <dg:DataGrid x:Name="dataGrid" AutoGenerateColumns="True"
   AlternationCount="2"
 
   HeadersVisibility="All"
   HorizontalGridLinesBrush="#DDDDDD"
   VerticalGridLinesBrush="#DDDDDD" Grid.ColumnSpan="2" Margin="0,0,28,26">
 
  <dg:DataGrid.Columns>
    <dg:DataGridTextColumn Header="ID Issue" Binding="{Binding Path=Id}" />
    <dg:DataGridTextColumn Header="Order Id" Binding="{Binding Path=OrderId}" />
    <dg:DataGridTextColumn Header="Is Done" Binding="{Binding Path=IsDone}" />
    <dg:DataGridTextColumn Header="Final Comment" Binding="{Binding Path=FinalComment}" />
    <dg:DataGridTextColumn Header="Actual Hours" Binding="{Binding Path=ActualHours}" />
    <dg:DataGridTextColumn Header="Group Id" Binding="{Binding Path=GroupId}" />
  </dg:DataGrid.Columns>
  </dg:DataGrid>
</Grid>
<Window.Resources>
  <Style x:Key="columnHeaderStyle" TargetType="{x:Type dg:DataGridColumnHeader}">
  <Setter Property="Background">
    <Setter.Value>
    <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
      <LinearGradientBrush.GradientStops>
      <GradientStop Color="Navy" Offset="0" />
      <GradientStop Color="LightBlue" Offset="1" />
      </LinearGradientBrush.GradientStops>
    </LinearGradientBrush>
    </Setter.Value>
  </Setter>
  <Setter Property="Foreground" Value="White" />
  </Style>
  <Style x:Key="rowStyle" TargetType="dg:DataGridRow">
  <Setter Property="FontFamily" Value="Verdana" />
  <Setter Property="FontSize" Value="10" />
  <Style.Triggers>
    <Trigger Property="AlternationIndex" Value="0">
    <Setter Property="Background" Value="White" />
    </Trigger>
    <Trigger Property="AlternationIndex" Value="1">
    <Setter Property="Background" Value="#DDDDDD" />
    </Trigger>
    <Trigger Property="IsMouseOver" Value="True">
    <Setter Property="Background" Value="#BBBBBB" />
    </Trigger>
  </Style.Triggers>
  </Style>
</Window.Resources>

And the WINDOWS.XAML.CS

Issuereference.Tasks issueRef = new Issuereference.Tasks();
Issuereference.TASK[] tasksList = issueRef.GetTasks(39);
dataGrid.ItemsSource = tasksList.ToList();
  dipa ahuja replied to srikar
19-Sep-11 06:48 AM
Untitled document
Step 1 : Write this code in .cs
 
public Form1()
{
 InitializeComponent();
  string connString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True";
 
  SqlDataAdapter da = new SqlDataAdapter("Select * from emp1", connString);
 DataSet ds = new DataSet();
 
  da.Fill(ds);
 dataGrid1.DataContext = ds;    
}
Step 2 : set the properties of dataGrid this way:
 
<DataGrid  ItemsSource="{Binding Path=Tables[0]}"   
    Margin="10"
    x:Name="dataGrid1"   
    ColumnHeaderHeight="30" AutoGenerateColumns="True"   
    CanUserSortColumns="False">
</DataGrid>
 
  aneesa replied to srikar
20-Sep-11 12:13 AM

<Button Height="23" Margin="0,12,35,0" Name="button1" VerticalAlignment="Top" HorizontalAlignment="Right" Width="46" Click="button1_Click">Go</Button>

<ListView Name="listView1" Margin="0,41,0,0">

<ListView.View>

<GridView>

<GridViewColumn Header="User_Name" Width="100" DisplayMemberBinding="{Binding Path=User_Name}"/>

<GridViewColumn Header="Project_Name" Width="100" DisplayMemberBinding="{Binding Path=Project_Name}" />

<GridViewColumn Header="CD_Name" Width="100" DisplayMemberBinding="{Binding Path=CD_Name}"/>

<GridViewColumn Header="IsOracle" Width="100" DisplayMemberBinding="{Binding Path=IsOracle}" />

</GridView>

</ListView.View>

</ListView>

</Grid>

</Window>



private void button1_Click(object sender, RoutedEventArgs e)

{

DataSet ds = new DataSet();

string sql = "select * from tblOTRecord order by Project_Name";

ds = ClsDBAccess.mGetOrcDataset(sql, ClsDBAccess.eConn.INTRANET); // Custom method, it is ok, getting rows

if(ds.Tables[0].Rows.Count > 0)

{

listView1.ItemSource= ds.Tables[0].DefaultView;


}

}

NOTE:Please add this property in your list view

<ListView Name="listView1" Margin="0,41,0,0" ItemSource="{Binding}">
////
</ListView >

Create New Account
help
choosen the Blog post from here This means the installation should be on a single server as Domain Controller , as MS SQL database server and as MOSS2007 server farm. Only one uses should be used. Thats what I have done, I followed the I am reading the logfiles placed under "c: \ program files \ common files \ microsoft shared \ web server extensions \ 12 \ logs". I don't find any relavant information regarding authentication or what else Anmeldung.' Source: '.Net SqlClient Data Provider' Number: 4060 State: 1 Class: 11 Procedure: '' LineNumber: 65536 Server: 'd-it5-sptest-dc' 03 / 04 / 2010 13:53:11.35 OWSTIMER.EXE (0x0980) 0x0988 spadmin'.' Source: '.Net SqlClient Data Provider' Number: 18456 State: 1 Class: 14 Procedure: '' LineNumber: 65536 Server: 'd-it5-sptest-dc' 03 / 04 / 2010 13:53:11.37 OWSTIMER.EXE (0x0980) 0x0988 Windows SharePoint Services Database 6y63 Critical SQL Database 'SharePoint_07_Config' on SQL Server instance 'd-it5-sptest-dc' not found. Additional error information
radiobutton frm table. . ? plz help me hi, aspx page code < asp:RadioButtonList id = "RadioButtonList1" runat = "server" > < / asp:RadioButtonList > < asp:Button ID = "btnTest" Runat = "server" Text = "Submit" > < / asp:Button > code-behind code. protected System.Web.UI.WebControls.Button btnTest; protected Load BindData() End Sub Sub BindData() Dim strConn As String strConn = "USER = ssdsa;PASSWORD = asdqe;SERVER = dddeeeaaa;DATABASE = Emp" Dim MySQL As String = "Select empno, empname from gr" Dim MyConn As 0 Transitional / / EN" "http: / / www.w3.org / TR / xhtml1 / DTD / xhtml1-transitional.dtd"> < script runat = "server" > public int score = 0; void scorefunction(Object sender, WizardNavigationEventArgs e) { if (RBL1.SelectedValue = = "a" ) { score msg.Text = score.ToString(); } < / script > < html xmlns = "http: / / www.w3.org / 1999 / xhtml" > < head runat = "server" > < title > Linear Wizard < / title > < / head > < body > < form id = "form1" runat = "server" > < div align = center > < asp:Wizard ID = "Wizard1" runat = "server" BackColor = "#FFFBD6" BorderColor = "#FFDFAD" onfinishbuttonclick = "scorefunction" Height = "160px" Width = "480px" ActiveStepIndex = "0" BorderWidth = "0px" Font Small" SideBarButtonStyle-Font-Bold = "true" SideBarStyle-BackColor = "AliceBlue" SideBarStyle-BorderColor = "Red" > < WizardSteps > < asp:WizardStep runat = "server" id = step1 StepType = "Start" > 1.When did India got independence? < asp:RadioButtonList ID = "RBL1" runat
There is an error like Error :The project could not be deployed to the 'localhost' server because of the following connectivity problems : A connection cannot be made. Ensure that the server is running. To verify or update the name of the target server, right-click on the project in Solution Explorer, select Project Properties, click on the Deployment tab, and then enter the name of the server. i m not able to deploy. Plz tell me wht are the configuration of this http: / / msdn.microsoft.com / en-us / library / ms175672.aspx For cube building, you can use SQL Server 2000 Analysis Services, SQL Server 2005 Analysis Services, or SQL Server 2008 Analysis Services. This article describes requirements for using
Any one send frequently asked Important questions in C# .Net, ADO .Net, Asp .Net and Sql Server. . . . . . . . tx in Advance. . . . . . Hi, Find this. . (B)What is an IL? (B)What is a objects in Remoting? (A) What are the ways in which client can create object on server in CAO model? (A) Are CAO stateful in nature? (A) To create objects in CAO page ? (I) Can we post and access view state in another application? (I) What is SQL Cache Dependency in ASP.NET 2.0? (I) How do we enable SQL Cache Dependency in ASP.NET 2.0? (I) What is Post Cache substitution? (I) Why Config”? (B) What is a SESSION and APPLICATION object? (A) What is the difference between ‘Server.Transfer’ and ‘response. Redirect’ ? (A)What is the difference between Authentication and authorization? (I) what proper? (A) If client side validation is enabled in your Web page, does that mean server side code is not run. (A)Which JavaScript file is referenced for validating the validators A)What is the use of <%@ page aspcompat = true %> attribute? B) Explain the differences between Server-side and Client-side code? (I)Can you explain Forms authentication in detail? (A)How
attempted to be installed. [08 / 10 / 11, 14:26:01] VS70pgui: [2] DepCheck indicates Microsoft SQL Server Compact 3.5 SP2 (x86) ENU was not attempted to be installed. [08 / 10 / 11, 14:26:01] VS70pgui: [2] DepCheck indicates Visual Studio 2010 Tools for SQL Server Compact 3.5 SP2 ENU was not attempted to be installed. [08 / 10 / 11, 14 attempted to be installed. [08 / 10 / 11, 14:26:02] VS70pgui: [2] DepCheck indicates Microsoft SQL Publishing Wizard 1.4 was not attempted to be installed. [08 / 10 / 11, 14:26:02] VS70pgui: [2] DepCheck indicates Microsoft SQL Server System CLR Types was not attempted to be installed. [08 / 10 / 11, 14:26:02 VS70pgui: [2] DepCheck indicates Microsoft SQL Server 2008 R2 Management Objects was not attempted to be installed. [08 / 10 / 11, 14