Tuesday, August 17, 2010

View Doctor Details Webpage

Doctor Details

Gridview

>asp:GridView ID="gvDoctors" runat="server" AutoGenerateColumns="false" AllowPaging="true"
PageSize="5" Width="100%" GridLines="Both" OnRowDataBound="gvDoctors_RowDataBound"
AllowSorting="true" OnSelectedIndexChanging="gvDoctors_SelectedIndexChanging"
OnSorting="gvDoctors_Sorting">


>Columns>
>asp:TemplateField>
>asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName"
HeaderStyle-CssClass="name" />
>asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName"
HeaderStyle-CssClass="name" />
>asp:BoundField DataField="City" HeaderText="City" SortExpression="City" HeaderStyle-CssClass="name" />
>asp:BoundField DataField="State" HeaderText="State" SortExpression="State" HeaderStyle-CssClass="name" />
>asp:BoundField DataField="ZipCode" HeaderText="ZipCode" SortExpression="ZipCode"
HeaderStyle-CssClass="name" />
>asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" HeaderStyle-CssClass="name" />
>asp:BoundField DataField="HomePhone" HeaderText="Home Phone" SortExpression="HomePhone"
HeaderStyle-CssClass="name" />
>asp:BoundField DataField="LicenceNumber" HeaderText="Licence Number" SortExpression="LicenceNumber"
HeaderStyle-CssClass="name" />
>%-- >asp:TemplateField ItemStyle-CssClass="hyperlink">
>ItemTemplate>
>asp:HyperLink ID="hlnkView" runat="server" CssClass="hyperlink" NavigateUrl='<%#String.Concat("/AMSWeb/ViewDoctors.aspx?stat=doct&did=",Eval("doctorid")) %>'>View
|>asp:HyperLink ID="hlnkEdit" runat="server" CssClass="hyperlink" NavigateUrl='>%#String.Concat("/AMSWeb/ModifyDoctor.aspx?stat=doct&did=",Eval("doctorid")) %>'>Edit>/asp:HyperLink>
|>asp:HyperLink ID="HyperLink2" runat="server" CssClass="hyperlink" NavigateUrl='>%#String.Concat("/AMSWeb/doctorappointments.aspx?stat=doct&did=",Eval("doctorid")) %>' >/asp:HyperLink>
>asp:HyperLink ID="HyperLink1" runat="server" CssClass="hyperlink" NavigateUrl='>%#String.Concat("/AMSWeb/doctorschedule.aspx?stat=doct&did=",Eval("doctorid")) %>'
Visible="false">Set Schedule>/asp:HyperLink>
>/ItemTemplate>
>/asp:TemplateField>--%>
>/Columns>
>/asp:GridView>


buttons


>input id="btnView" name="btnView" class="submitbutton" type="button" value="View"
onclick="return ViewDoctor();" />

>input id="btnEdit" name="btnEdit" class="submitbutton" type="button" value="Edit"
onclick="return EditDoctor();" />

Doctor Webpage.cs

Doctor.CS

INSERT


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using AMS.BO;
using AMS.BLL;

public partial class adddoctor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GetSpecilizations();
}
}

private void GetSpecilizations()
{
DoctorsBLL objCPBLL = new DoctorsBLL();
DataSet ds = objCPBLL.GetSpecilizations();
ddlSpecializationId.DataSource = ds;
ddlSpecializationId.DataBind();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
DoctorsBLL objCPBLL = new DoctorsBLL();
UsersBLL objUserBLL = new UsersBLL();
DoctorsBO objDoctorBO = new DoctorsBO();
UsersBO objUserBO = new UsersBO();
int doctorid = -1;
int userid = AddUser();

if (userid != 0)
{
doctorid = AddDoctor(userid);
}

if (doctorid == -1)
{

objUserBO.Type = "Delete";
objUserBLL.UsersOperations(objUserBO);

string alert = ">script language=javascript>alert('Error Occured Doctor Details..');>/script>";
Page.ClientScript.RegisterStartupScript(typeof(Page), "Alert", alert);

}
else
{
string alert = ">script language=javascript>alert('Doctor Successfully Inserted');>/script>";
Response.Write(alert);
//Page.ClientScript.RegisterStartupScript(typeof(Page), "Alert", alert);
Response.Redirect("/AMSWeb/doctors.aspx");

}
}

private int AddUser()
{
UsersBLL objBLL = new UsersBLL();
UsersBO objBO = new UsersBO();
objBO.UserName = txtUserName.Text;
objBO.Password = txtPassword.Text;
objBO.Role = 1;
objBO.Email = txtEmail.Text;
if (chkStatus.Checked)
{
objBO.Status = 1;
}
else
{
objBO.Status = 0;
}
objBO.EnteredDate = Convert.ToString(DateTime.Now);
objBO.Type = "Insert";
objBO = objBLL.UsersOperations(objBO);
if (objBO.NewUserId != 0)
{
return objBO.NewUserId;
}
else
return 0;

}
private int AddDoctor(int userid)
{
DoctorsBLL objBLL = new DoctorsBLL();
DoctorsBO objBO = new DoctorsBO();
objBO.UserId = userid;
objBO.FirstName = txtFirstName.Text;
objBO.LastName = txtLastName.Text;
objBO.MiddleName = txtMiddleName.Text;
objBO.SSN = txtSSN.Text;
objBO.DOB = txtDOB.Text;
objBO.Gender = rdolstGender.SelectedItem.Text;
objBO.Age = Convert.ToInt32(txtAge.Text);
objBO.Address = txtAddress.Text;
objBO.City = txtCity.Text;
objBO.State = txtState.Text;
objBO.ZipCode = txtZipCode.Text;
objBO.Email = txtEmail.Text;
objBO.HomePhone = txtHomePhone.Text;
objBO.WorkPhone = txtWorkPhone.Text;
objBO.Mobile = txtMobile.Text;
objBO.Fax = txtFax.Text;
objBO.SpecilizationId = Convert.ToInt32(ddlSpecializationId.SelectedItem.Value);
objBO.RegistrationNumber = txtRegistrationNo.Text;
objBO.LicenceNumber = txtLicenceNo.Text;


objBO.Type = "Insert";
objBO = objBLL.DoctorOperations(objBO);
if (objBO.DoctorId == 1)
return 1;
else
return -1;
}
}

UPDATE

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using AMS.BO;
using AMS.BLL;

public partial class ClaimantAdministrator : System.Web.UI.Page
{
int ClaimantAdminID
{
get
{
int claimantAdminID = 0;

if (Request.QueryString["cid"] != null && Request.QueryString["cid"].Length > 0)
{
claimantAdminID = Convert.ToInt32(Request.QueryString["cid"]);
Session["claimantID"] = claimantAdminID;
}
else if (Session["claimantID"] != null)
claimantAdminID = Convert.ToInt32(Session["cid"]);
return claimantAdminID;
}
}

protected void Page_Load(object sender, EventArgs e)
{
btnSubmit.Attributes.Add("onclick", "return validate();");

if (!Page.IsPostBack)
{
GetUSStates();
if (ClaimantAdminID != 0)
DisplayCalimantAdministrator();
}
}

private void DisplayCalimantAdministrator()
{
ClaimantAdminInformationBLL objCABLL = new ClaimantAdminInformationBLL();
ClaimantAdminInformationBO objCABO = new ClaimantAdminInformationBO();
objCABO.Type = "SelectByClaimantAdminID";
objCABO.ClaimantAdminID = ClaimantAdminID;
DataSet ds = new DataSet();
objCABLL.ClaimantAdminOperations(objCABO);
ds = objCABO.GetUSStates;
if (ds.Tables[0].Rows.Count > 0)
{
DataTable dt = ds.Tables[0];
ViewState["ClaimantAdminID"] = ds.Tables[0].Rows[0]["ClaimantAdminID"].ToString();
txtClaimantAdminName.Text = ds.Tables[0].Rows[0]["ClaimantAdminName"].ToString();
txtClaimantAdminAddress.Text = ds.Tables[0].Rows[0]["Address"].ToString();
txtClaimantAdminCity.Text = ds.Tables[0].Rows[0]["City"].ToString();
ddlState.Text = ds.Tables[0].Rows[0]["State"].ToString();
txtClaimantAdminPhone.Text = ds.Tables[0].Rows[0]["PhoneNo"].ToString();
txtClaimantAdminZipCode.Text = ds.Tables[0].Rows[0]["ZipCode"].ToString();
txtClaimantAdminFax.Text = ds.Tables[0].Rows[0]["Fax"].ToString();
txtClaimantAdminEmail.Text = ds.Tables[0].Rows[0]["Email"].ToString();

txtCPName.Text = ds.Tables[0].Rows[0]["ContactPersonName"].ToString();
txtCPSSN.Text = ds.Tables[0].Rows[0]["ContactPersonSSN"].ToString();
txtCPTitle.Text = ds.Tables[0].Rows[0]["ContactPersonTitle"].ToString();
txtCPPhone.Text = ds.Tables[0].Rows[0]["ContactPersonPhoneNo"].ToString();
txtCPMobile.Text = ds.Tables[0].Rows[0]["ContactPersonMobileNo"].ToString();
txtCPEmail.Text = ds.Tables[0].Rows[0]["ContactPersonEmail"].ToString();
}
}
private void GetUSStates()
{
ClaimantAdminInformationBLL objBLL = new ClaimantAdminInformationBLL();
ClaimantAdminInformationBO objBO = new ClaimantAdminInformationBO();

DataSet ds = new DataSet();
ds = objBLL.GetUSStates();
ddlState.DataSource = ds;

ddlState.DataTextField = "USStateName";
ddlState.DataValueField = "USStateCd";
ddlState.DataBind();

ddlState.Items.FindByText("California").Selected = true;
}

protected void btnSubmit_Click(object sender, EventArgs e)
{
ClaimantAdminInformationBLL objCABLL = new ClaimantAdminInformationBLL();
ClaimantAdminInformationBO objCABO = new ClaimantAdminInformationBO();
objCABO.ClaimantAdminName = txtClaimantAdminName.Text;
objCABO.Address = txtClaimantAdminAddress.Text;
objCABO.City = txtClaimantAdminCity.Text;
objCABO.State = ddlState.SelectedItem.Value;
objCABO.ZipCode = txtClaimantAdminZipCode.Text;
objCABO.PhoneNo = txtClaimantAdminPhone.Text;
objCABO.Fax = txtClaimantAdminFax.Text;
objCABO.Email = txtClaimantAdminEmail.Text;
objCABO.ContactPersonName = txtCPName.Text;
objCABO.ContactPersonTitle = txtCPTitle.Text;
objCABO.ContactPersonSSN = txtCPSSN.Text;
objCABO.ContactPersonPhoneNo = txtCPPhone.Text;
objCABO.ContactPersonMobileNo = txtCPMobile.Text;
objCABO.ContactPersonEmail = txtCPEmail.Text;

if (ViewState["ClaimantAdminID"] == null)
objCABO.Type = "Insert";
else
{
objCABO.Type = "Update";
objCABO.ClaimantAdminID = Convert.ToInt32(ViewState["ClaimantAdminID"]);
}
objCABLL.ClaimantAdminOperations(objCABO);

Response.Redirect("ClaimantAdministrator.aspx?stat=comp");

//if (objCABO.ClaimantAdminID == 0)
//{
// string str = "";
// Page.ClientScript.RegisterStartupScript(typeof(Page), "success", str);
//}
//else
//{
// string str = "";
// Page.ClientScript.RegisterStartupScript(typeof(Page), "success", str);
//}
}
}

Doctor Webpage

Doctor Add page

textbox
>asp:TextBox ID="txtFirstName" runat="server" CssClass="TextBox">>/asp:TextBox>
rediobutton
>asp:RadioButtonList ID="rdolstGender" runat="server"
RepeatDirection="Horizontal">
>asp:ListItem Selected="True">Male>/asp:ListItem>
>asp:ListItem>Female>/asp:ListItem>
>/asp:RadioButtonList>
dropdownbutton
>asp:DropDownList ID="ddlSpecializationId" runat="server"
DataTextField="Specilization" DataValueField="SpecilizationId"
CssClass="TextBox">
>asp:ListItem Value="-1" >Select Specialization>/asp:ListItem>
>asp:ListItem Value="0">Cardiologist>/asp:ListItem>
>asp:ListItem Value="1">Physiotheraphist>/asp:ListItem>
>asp:ListItem Value="2">Dermatologist>/asp:ListItem>
>asp:ListItem Value="3">Gynaecologist>/asp:ListItem>
>/asp:DropDownList>
button
>asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="Button"
onclick="btnSubmit_Click" />

>asp:Button ID="btnCancel" runat="server" Text="Cancel" CssClass="Button"
CausesValidation="False" />

DLL (Data Logic Layar )

DoctorDAL


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using AMS.BO;
using AMS.DAL;

namespace AMS.BLL
{
public class DoctorsBLL
{
public DoctorsBO DoctorOperations(DoctorsBO objBO)
{
DoctorsDAL objDAL = new DoctorsDAL();
return objDAL.DoctorOperations(objBO);
}
public DataSet GetSpecilizations()
{
DoctorsDAL objDAL = new DoctorsDAL();
return objDAL.GetSpecilizations();
}
}
}

DAL ( DATA ACCESS LAYAER )

DoctorDAL

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using AMS.BO;

namespace AMS.DAL
{
public class DoctorsDAL:DALTemplateClass
{
private SqlConnection myConn;
public DoctorsBO DoctorOperations(DoctorsBO objBO)
{
// Create Instance of Connection and Command Object

myConn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["AMSDB"]);
SqlCommand myComm = new SqlCommand("AMS_Doctors_Operations", myConn);
SqlDataAdapter da = new SqlDataAdapter();

// Mark the Command as a SPROC

myComm.CommandType = CommandType.StoredProcedure;

myComm.Parameters.AddWithValue("@DoctorId", objBO.DoctorId);
myComm.Parameters.AddWithValue("@Hid", objBO.Hid);
myComm.Parameters.AddWithValue("@UserId", objBO.UserId);
myComm.Parameters.AddWithValue("@SalutationId", objBO.SalutationId);
myComm.Parameters.AddWithValue("@FirstName", objBO.FirstName);
myComm.Parameters.AddWithValue("@LastName", objBO.LastName);
myComm.Parameters.AddWithValue("@MiddleName", objBO.MiddleName);
myComm.Parameters.AddWithValue("@SSN", objBO.SSN);
myComm.Parameters.AddWithValue("@DOB", objBO.DOB);
myComm.Parameters.AddWithValue("@Gender", objBO.Gender);
myComm.Parameters.AddWithValue("@Age", objBO.Age);
myComm.Parameters.AddWithValue("@Address", objBO.Address);
myComm.Parameters.AddWithValue("@City", objBO.City);
myComm.Parameters.AddWithValue("@State", objBO.State);
myComm.Parameters.AddWithValue("@ZipCode", objBO.ZipCode);
myComm.Parameters.AddWithValue("@Email", objBO.Email);
myComm.Parameters.AddWithValue("@HomePhone", objBO.HomePhone);
myComm.Parameters.AddWithValue("@WorkPhone", objBO.WorkPhone);
myComm.Parameters.AddWithValue("@Mobile", objBO.Mobile);
myComm.Parameters.AddWithValue("@Fax", objBO.Fax);
myComm.Parameters.AddWithValue("@SpecilizationId", objBO.SpecilizationId);
myComm.Parameters.AddWithValue("@RegistrationNumber", objBO.RegistrationNumber);
myComm.Parameters.AddWithValue("@LicenceNumber", objBO.LicenceNumber);
myComm.Parameters.AddWithValue("@Type", objBO.Type);



// Open the connection and execute the Command

try
{

myConn.Open();
if (objBO.Type == "Insert" || objBO.Type == "Update")
{

myComm.ExecuteNonQuery();
objBO.DoctorId = 1;

}
if (objBO.Type == "SelectAll" || objBO.Type == "SelectById" || objBO.Type=="SelectByUserId"
|| objBO.Type == "SelectByHospitalId" || objBO.Type == "Search" )
{

DataSet ds = new DataSet();
da.SelectCommand = myComm;
da.Fill(ds);
objBO.DoctorsDS = ds;

}
return objBO;
}
catch (Exception ex)
{
MessageDescription = ex.Message;
return null;
}
finally
{
myConn.Close();
myComm.Dispose();
da.Dispose();
}


}

public DataSet GetSpecilizations()
{
// Create Instance of Connection and Command Object

myConn = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["AMSDB"]);
SqlCommand myComm = new SqlCommand("AMS_Specializations_Operations", myConn);
SqlDataAdapter da = new SqlDataAdapter();
// Mark the Command as a SPROC


// Open the connection and execute the Command

try
{


DataSet ds = new DataSet();
da.SelectCommand = myComm;
da.Fill(ds);


return ds;
}
catch (Exception ex)
{
MessageDescription = ex.Message;
return null;
}
finally
{
myConn.Close();
myComm.Dispose();
da.Dispose();
}

}
}
}



Connection DB


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace AMS.DAL
{
public class ConnectionDB
{
private static SqlConnection _dbConnection;

public static void CloseConnection()
{
if (_dbConnection.State != ConnectionState.Closed)
{
_dbConnection.Close();
}
}

public static SqlConnection GetConnection()
{
_dbConnection = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["AMSDB"]);
_dbConnection.Open();
return _dbConnection;
}


}

}

web.config

>appSettings>
>add key="AMSDB" value="server=SYS;User Id=sa;Password=123456;database=AMSDBNew;Connection Timeout=10000;"/>
>!---->
>add key="autoSuggestConnectionString" value="server=.\SQLEXPRESS;Integrated Security=SSPI;database=northwind;provider=SQLNCLI.1"/>
>add key="DocId" value="1"/>
>add key="HId" value="2"/>
>add key="CompanyID" value="31"/>
>add key="ContactPersonID" value="23"/>
>add key="PhysicalPathofPDF" value="D:\AMS\\AMSWeb\\Documents\\"/>
>!-- EMail Credentials -->
>add key="networkCredentialMailId" value="gajulamk@gmail.com"/>
>add key="networkCredentialMailPassword" value="gajula"/>
>add key="defaultFromMailId" value="ams.gajulamk@gmail.com"/>
>add key="smtpClient" value="smtp.gmail.com"/>
>add key="port" value="587"/>
>!-- End EMail-->
>/appSettings>
>connectionStrings/>
>system.web>

>!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
>customErrors mode="Off"/>
>compilation debug="true">
>assemblies>
>add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
>add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
>add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
>add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
?add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
>add assembly="System.Web.Extensions.Design, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

>/assemblies>
>/compilation>

BO ( Bussiness Objectives )

DoctorBO first

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace AMS.BO
{
public class DoctorsBO:ProfileBO
{
private int _DoctorId;
public int DoctorId
{
get { return _DoctorId; }
set { _DoctorId = value; }
}
private string _DOB;
public string DOB
{
get { return _DOB; }
set { _DOB = value; }
}
private string _Gender;
public string Gender
{
get { return _Gender; }
set { _Gender = value; }
}
private int _Age;
public int Age
{
get { return _Age; }
set { _Age = value; }
}

private string _Address;
public string Address
{
get { return _Address; }
set { _Address = value; }
}
private string _City;
public string City
{
get { return _City; }
set { _City = value; }
}
private string _State;
public string State
{
get { return _State; }
set { _State = value; }
}
private string _ZipCode;
public string ZipCode
{
get { return _ZipCode; }
set { _ZipCode = value; }
}
private int _SpecilizationId;
public int SpecilizationId
{
get { return _SpecilizationId; }
set { _SpecilizationId = value; }
}
private string _RegistrationNumber;
public string RegistrationNumber
{
get { return _RegistrationNumber; }
set { _RegistrationNumber = value; }
}
private string _LicenceNumber;
public string LicenceNumber
{
get { return _LicenceNumber; }
set { _LicenceNumber = value; }
}

private DataSet _DoctorsDS;
public DataSet DoctorsDS
{
get { return _DoctorsDS; }
set { _DoctorsDS = value; }
}

}
}


DoctorBO Second


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace AMS.BO
{
public class DoctorsBO:ProfileBO
{
public int DctorID { get; set; }
public string DOB{ get; set; }
public string Gender{ get; set; }
public string Age{ get; set; }
public string Address{ get; set; }
public string City{ get; set; }
public string ToDate { get; set; }
}
}

Monday, March 8, 2010

Using a WPF ListView as a DataGrid

Many people like to view data in a grid format of rows and columns. WPF did not come with a data grid control that automatically creates rows and columns for you based on the object you pass it. However, the WPF Toolkit can be downloaded from CodePlex.com that does contain a DataGrid control. This DataGrid gives you the ability to pass it a DataTable or a Collection class and it will automatically figure out the columns or properties and create all the columns for you and display the data.

The DataGrid control also supports editing and many other features that you might not always need. This means that the DataGrid does take a little more time to render the data. If you want to just display data (see Figure 1) in a grid format, then a ListView works quite well for this task. Of course, you will need to create the columns for the ListView, but with just a little generic code, you can create the columns on the fly just like the WPF Toolkit’s DataGrid.

ListView as a DataGrid - Figure 1

Figure 1: A List of Data using a ListView


A Simple ListView Control

The XAML below is what you would use to create the ListView shown in Figure 1. However, the problem with using XAML is you have to pre-define the columns. You cannot re-use this ListView except for “Product” data.


>ListView x:Name="lstData"
ItemsSource="{Binding}">
>ListView.View>
>GridView>
>GridViewColumn Header="Product ID"
Width="Auto"
DisplayMemberBinding="{Binding Path=ProductId}" />
>GridViewColumn Header="Product Name"
Width="Auto"
DisplayMemberBinding="{Binding Path=ProductName}" />
>GridViewColumn Header="Price"
Width="Auto"
DisplayMemberBinding="{Binding Path=Price}" />
>/GridView>
>/ListView.View>
>/ListView>

So, instead of creating the GridViewColumn’s in XAML, let’s learn to create them in code to create any amount of columns in a ListView.

Create GridViewColumn’s From Data Table

To display multiple columns in a ListView control you need to set its View property to a GridView collection object. You add GridViewColumn objects to the GridView collection and assign the GridView to the View property. Each GridViewColumn object needs to be bound to a column or property name of the object that the ListView will be bound to. An ADO.NET DataTable object contains a collection of columns, and these columns have a ColumnName property which you use to bind to the GridViewColumn objects.

Listing 1 shows a sample of reading and XML file into a DataSet object. After reading the data a GridView object is created. You can then loop through the DataTable columns collection and create a GridViewColumn object for each column in the DataTable. Notice the DisplayMemberBinding property is set to a new Binding to the ColumnName in the DataTable.

C#
private void FirstSample()
{
// Read the data
DataSet ds = new DataSet();
ds.ReadXml(GetCurrentDirectory() + @"\Xml\Product.xml");

// Create the GridView
GridView gv = new GridView();

// Create the GridView Columns
foreach (DataColumn item in ds.Tables[0].Columns)
{
GridViewColumn gvc = new GridViewColumn();
gvc.DisplayMemberBinding = new Binding(item.ColumnName);
gvc.Header = item.ColumnName;
gvc.Width = Double.NaN;
gv.Columns.Add(gvc);
}

// Setup the GridView Columns
lstData.View = gv;
// Display the Data
lstData.DataContext = ds.Tables[0];
}

VB.NET
Private Sub FirstSample()
' Read the data
Dim ds As New DataSet()
ds.ReadXml(GetCurrentDirectory() & "\Xml\Product.xml")

' Create the GridView
Dim gv As New GridView()

' Create the GridView Columns
For Each item As DataColumn In ds.Tables(0).Columns
Dim gvc As New GridViewColumn()
gvc.DisplayMemberBinding = New Binding(item.ColumnName)
gvc.Header = item.ColumnName
gvc.Width = [Double].NaN
gv.Columns.Add(gvc)
Next

' Setup the GridView Columns
lstData.View = gv
' Display the Data
lstData.DataContext = ds.Tables(0)
End Sub
Listing 1: Loop through the DataTable columns collection to create GridViewColumn objects

A Generic Method for Creating a GridView

Instead of having to write the code shown in Listing 1 for each ListView you wish to create, you can create a generic method that given any DataTable will return a GridView column collection. Listing 2 shows how you can simplify the code in Listing 1 by setting up a class called WPFListViewCommon and create a method called CreateGridViewColumns that returns your GridView.

C#
private void DataTableSample()
{
// Read the data
DataSet ds = new DataSet();
ds.ReadXml(GetCurrentDirectory() + @"\Xml\Product.xml");

// Setup the GridView Columns
lstData.View =
WPFListViewCommon.CreateGridViewColumns(ds.Tables[0]);
lstData.DataContext = ds.Tables[0];
}

VB.NET
Private Sub DataTableSample()
' Read the data
Dim ds As New DataSet()
ds.ReadXml(GetCurrentDirectory() & "\Xml\Product.xml")

' Setup the GridView Columns
lstData.View = _
WPFListViewCommon.CreateGridViewColumns(ds.Tables(0))
lstData.DataContext = ds.Tables(0)
End Sub
Listing 2: Call a generic method to create GridViewColumns.

The CreateGridViewColumns Method

The CreateGridViewColumns method will take a DataTable as a parameter and create a GridView object with a GridViewColumn object in its collection for each column in your DataTable.

C#
public static GridView CreateGridViewColumns(DataTable dt)
{
// Create the GridView
GridView gv = new GridView();
gv.AllowsColumnReorder = true;

// Create the GridView Columns
foreach (DataColumn item in dt.Columns)
{
GridViewColumn gvc = new GridViewColumn();
gvc.DisplayMemberBinding = new Binding(item.ColumnName);
gvc.Header = item.ColumnName;
gvc.Width = Double.NaN;
gv.Columns.Add(gvc);
}

return gv;
}

VB.NET
Public Shared Function CreateGridViewColumns _
(ByVal dt As DataTable) As GridView
' Create the GridView
Dim gv As New GridView()
gv.AllowsColumnReorder = True

' Create the GridView Columns
For Each item As DataColumn In dt.Columns
Dim gvc As New GridViewColumn()
gvc.DisplayMemberBinding = New Binding(item.ColumnName)
gvc.Header = item.ColumnName
gvc.Width = [Double].NaN
gv.Columns.Add(gvc)
Next

Return gv
End Function

Listing 3: The CreateGridViewColumns method takes a DataTable and creates GridViewColumn objects in a GridView.
By separating this method out into a class you can call this method anytime you want to create a ListView with a collection of columns from a DataTable.