Foreign Key relation like Database in Silverlight using ComboBox

debal_saha-9451
Posted by in Silverlight category on for Intermediate level | Points: 250 | Views : 7490 red flag

Sometimes we need to make our users for their convenient not to remember the relationship between Id number with related to its designations. For E.g. in a company there is “Projectmanager”, “developer”, “Sales” etc … persons & they have their individual primary Id with those Ids are also may be related with their designations(or Employee Type.)


 Download source code for Foreign Key relation like Database in Silverlight using ComboBox

Introduction

Generally these scenarios are lots of use in data base where foreign Key is used to Express relation between one table with other table. Ok, I find this beautiful article which comes in my mail , so why not to share this. You can  also get this http://www.pdsa.com , there is also other solutions of Silvelight u can get. I implement this in my own way in this small application in a Simple Coding .

There is lots of things can be improvement but whatever I can I do it .

The First Picture :

pic-1

This is the Data grid which is fill with some information. Now , when the User want to pick from a Selection of  Items as an Example , EmployeeTypeId for Employee Data then he/she need not remember the corresponding data i.e. that Id Person may be “Projectmanager”,”Salesmanager” or etc. It will automatically call in the Combobox. Lets look the Image .

pic-2

Ok, Now lets built this application .

  1. Open Silverlight Project whatever wish give the name of the application in VS2010.
  2. Now , make 4 folder & their names are Model, View , ViewModel , Providers. Add new Classes (in C#)in this folders . Lets see the pic – 3 will clear this .
  3. PL ignore the Styles folder . Its nothing but implement the Styles for the Controls of the Silverlight.
  4. Now, its for Coding . First in the Employee.cs  class which is located in Model Folder. Just need to write the properties for this Class. Here is the Code .

public class Employee

{

public Employee()

{

// This is a default Constructor

}

public Employee(int id, string name, int empTypeId)

{

EmployeeId = id;

Name = name;

EmployeeTypeId = empTypeId;

}

public int EmployeeId { get; set; }

public string Name { get; set; }

public int EmployeeTypeId { get; set; }

}


pic - 3

   

    5. Now same in the EmployeeType.cs Class this is also in the Model folder. Here u can see the EmployeeTypeId &  EmpType these two properties . Here note to be point is that the EmployeeTypeId working as a foriegnkey in Employee.cs Class. Look the Code .

 

public class EmployeeType

{

public EmployeeType()

{

}

 

public EmployeeType(int id, string empType)

{

EmployeeTypeId = id;

EmpType = empType;

}

 

public int EmployeeTypeId { get; set; }

public string EmpType { get; set; }

}

  6. Now our 2 clasess are ready just need to bind in the Datagrid in MainApplication page, which is in View. But  wait before that we need to do others things . First in the Xaml page (Which is ur MainAppilication.Xaml) just drag and drop Datagrid from ToolBox . I take it inside row & column of main layout Grid. Upto now this is ok. But it don’t have any data because we did not pass any data information in the Model classes, just we create properties. Now its time to provide information. So we created provider Folder. Just make a Class name it details.


  7. In the details.cs class first we need use this using System.Collection.ObjectModel; namespace . Here we are creating 2 Methods that will contains the data. Using observation collection makes its simplify for collection of data. look at the code;

First method for providing data to Employee in the name of  GetEmployeeData().

public static class Details

{

public static ObservableCollection<Employee> GetEmployeeData()

{

ObservableCollection<Employee> emp = new ObservableCollection<Employee>()

{

new Employee{ EmployeeId = 1,EmployeeTypeId = 2, Name="Debal"},

new Employee{ EmployeeId = 2,EmployeeTypeId = 3, Name="Lanu"},

new Employee{ EmployeeId = 3,EmployeeTypeId = 4, Name="Das Singh"},

new Employee{ EmployeeId = 4,EmployeeTypeId = 3, Name="RamKumar"},

new Employee{ EmployeeId = 5,EmployeeTypeId = 2, Name="Wasington"},

};

return emp;

}

}

2nd Method is for providing data to Employeetype in the name of GetEmployeeType()

public static ObservableCollection<EmployeeType> GetEmployeeType()

{

ObservableCollection<EmployeeType> emptype = new ObservableCollection<EmployeeType>

{

new EmployeeType{EmployeeTypeId = 2, EmpType= "Developer"},

new EmployeeType{EmployeeTypeId = 3, EmpType= "SalesManager"},

new EmployeeType{EmployeeTypeId = 4, EmpType= "ProjectManager"},

};

return emptype;

}

    8.  Upto now this is lots . Now just show this data in datagrid. But before that need to make ViewModel class   name it as a DataBind.cs. This is as simply as I can . Just make 2 Public properties & add value in its. Look how .
 

public ObservableCollection<Employee> BindEmployee { get; set; }

public ObservableCollection<EmployeeType> BindEmployeeType { get; set; }

public DataBind()

{

BindEmployee = Details.GetEmployeeData();

BindEmployeeType = Details.GetEmployeeType();

}

   9. Just need to move in the Xaml page . Where I give the name of the datagrid is datagrid1. In the Code-Behind file first make an instance of the Class DataBind.(Which is in ViewModel folder)
 

    In the Constructor of the Code-Behind page of the MainApplication Xaml page . i.e. MyAppicationPage.xaml.cs page write the one line code which will fetch data from Provider class & bind it in the DataGrid. No need to write Binding options in xaml / design page or anthing . We did it in the Constructor because we want to show the data in datagrid when the page is first loaded . U do it as ur requirements.

public partial class MyAppicationPage : UserControl

{

DataBind d = new DataBind();

public MyAppicationPage()

{

InitializeComponent();

this.dataGrid1.ItemsSource = d.BindEmployee;

}

}

  10. Now , add this event in ur xaml datagrid . SelectionChanged="dataGrid1_SelectionChanged" .
Drag & Drop 2 Textboxes one Combobox in UI page . make the desing as same in Pic -2 . Take also 3 TextBlock from the ToolBox and  name them as u want . I give First TextBoxe name is Name="IDTextBox".
Second TextBox name is Name="NameTextBox"
Thrid is the Combobox wahic I give the name of  Name="EmployeeTypeCombobox"

  11. Lets solve the first 2 TextBoxes then come in Combobox . In the SelectionChanged Event (In the Page Code-Behind) need to write this code .

private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

this.IDTextBox.DataContext = dataGrid1.SelectedItem;

this.NameTextBox.DataContext = dataGrid1.SelectedItem;

}

But when will u run the Application & click one particular data in Datagrid in Browser . U will not able to see any changes in the TextBoxes . No data will bind in these TextBoxes becauses we did not write any Binding options or code for that in the textboxes . So , I did databinding in xaml page ,u can also do it dynamic binding . usually do prefer in Xaml . See one for First TextBox .

<TextBox Grid.Column="1"

Grid.Row="2" Height="23"

HorizontalAlignment="Left"

Margin="3,19,0,0"

Name="IDTextBox"

Text="{Binding EmployeeId}" <---------------- Note the Binding

VerticalAlignment="Top" Width="218"/>

Simialrly for the Second TextBox Which is for EmployeeName look at this :

<textbox height="23" horizontalalignment="Left" margin="4,18,0,0" name="NameTextBox"

verticalalignment="Top" width="218" text="{Binding Name}" grid.column="1" grid.row="3" />

   12. Now run ur application & see that when u select one item in datagrid its corresponding data are coming to the TextBoxes .But the Combobox doesn’t have any changes . Lets also do it . Its Some Complex so it step by step

First need bind items in the Combobox .  So, first look at the code in xaml.

<ComboBox Grid.Column="1" Grid.Row="4" Height="23"

HorizontalAlignment="Left" Margin="5,11,0,0"

Name="EmployeeTypeCombobox" ?-------------------------------Name of the Combobox

VerticalAlignment="Top"

DisplayMemberPath="EmpType"

ItemsSource="{Binding EmpType}" ?-----------------------------Binding.

Width="218"/>

Now , this is not enough to get the items in the Combobox. Again, Go to the Code-Behind pages , We need to bind it items in the Combobox when the page is first loaded . So, that when user select item from the datagrid it should display it in the Combobox as per requirement information . So , in the Constructor of this page write this code:

public MyAppicationPage()

{

InitializeComponent();

this.dataGrid1.ItemsSource = d.BindEmployee;

this.EmployeeTypeCombobox.ItemsSource = d.BindEmployeeType; *** This is Code u need to Write.

}

Remember "d" is the instance of the Class dataBind.

Now Run & check that ur Combobox is fill up with the data like : “Projectsmanages”,”Salesmanagers’,”developer” etc. Look the Pic -4

But When u Click on the datagrid there is no Changes occurring in Combobox. So for that interesting thing is left.

pic – 4

TO do that we need to correct our Combobox xaml code need to write 

SelectedValuePath="EmployeeTypeId"

SelectedValue="{Binding ElementName=dataGrid1, Path=SelectedItem.EmployeeTypeId}"


Now See that , when u click in the datagrid items ur Combobox also going chages as related with the EmployeeId anr its foriegnkey EmployeeTypeId . Is it not interesting ?

Up to Now this is one Example of how to using foriengKey in Silverlight Application without database . This is Simple & light-weight small application.

Want to jump other . Nice see this Example , we have 2 Combobox one is SelectCountry & other is Select State . I take for simplicity 3 Country & their name is “India” , ”Pakistan”, ”Bangladesh”. And take some names of these countries States like “WestBengal, Assam, etc …” for India, “Karachi, Islamabad” for Pakistan, and same some for Bangladesh.

Ok, when user Select one Country from the ComboBox its corresponding States will come in the Below ComboBox Dropdownlist. I also imlplement same logic as foreign key in the Previous .

Ok lets do it

    1. First Drag & drop 2 Combobox or do it from here copy & paste it in ur xaml page . But be sure the Grid.row & column as per ur UI design. So check it .

<ComboBox Height="23"

HorizontalAlignment="Left"

DisplayMemberPath="Countryname" ?----------------- It will Show only Country name in Combobox

ItemsSource="{Binding Countryname}" ?---------------Binding item

Margin="5,6,0,0"

Name="CountryComboBox" ?-------------------Name of the Combobox

VerticalAlignment="Top"

Width="218"

Grid.Column="1" Grid.Row="5" />

Ok, we do it one by one . Now go to the Classes of the Model find out Country what is u created now .  Write the code below . See every thing are similar the Employee Class.

public class Country

{

public Country()

{

// This is a default Constructor

}

 

public Country(int CId, string CName, int StateId)

{

this.CountryId = CId;

this.Countryname = CName;

this.StateId = StateId;

}

 

public int CountryId { get; set; }

public string Countryname { get; set; }

public int StateId { get; set; }

}

Ok , Now in the Providers Folder Find out the Details.cs class.  Wirte  these code to Provide Data for the Combobox.

public static ObservableCollection<Country> GetCountryname()

{

ObservableCollection<Country> count = new ObservableCollection<Country>()

{

new Country{CountryId = 1 , Countryname = "India" , StateId = 10},

new Country{CountryId = 2 , Countryname = "Pakisan" , StateId = 11},

new Country{CountryId = 3 , Countryname = "Bangladesh" , StateId = 12}

};

return count;

}

Now in the ViewModel Findout the DataBind.cs Class .  Make on Public Property & Bind this Property with the  The Method GetCountryname().

public ObservableCollection<Country> BindCountry { get; set; }

 

public DataBind()

{

BindCountry = Details.GetCountryname();

}

This is not end. Just one Step more. Go to the mainApplicationPageXaml.cs page in the Constructor write the follow code.

this.CountryComboBox.ItemsSource = d.BindCountry;

So run & see the output . Like the Pic -5 Image .     

pic-5

    2. Now the one Combo box is ready . Now lets go to state Combbobox. So in the State.cs Class which is in the Model Folder . Just write this code . Up to now it is became very familiar with u .

public class State

{

public State()

{

//this is a default constructor

}

 

public State(int id, string name)

{

this.StateId = id;

this.Statename = name;

}

 

public int StateId { get; set; }

public string Statename { get; set; }

}

     3. In the Provider Folder details.cs class we just write a method what is provide data for state class. The code Is below.

public static ObservableCollection<State> GetStatename()

{

ObservableCollection<State> state = new ObservableCollection<State>()

{

new State {StateId = 10, Statename = "Tripura"},

new State {StateId = 10, Statename = "Assam"},

new State {StateId = 10, Statename = "Rajastan"},

new State {StateId = 10, Statename = "Manipur"},

new State {StateId = 11, Statename = "karachi"},

new State {StateId = 11, Statename = "Baluchistan"},

new State {StateId = 11, Statename = "Islamabad"},

new State {StateId = 12, Statename = "Dhaka"},

new State {StateId = 12, Statename = "mayamsigh"},

new State {StateId = 12, Statename = "Silate"},

new State {StateId = 12, Statename = "Chhatagram"}

};

return state;

}

     4. That’s all. In the ViewModel folder Databind Class we need to bind this with a new property in the name  of  BindState. So the Code is the follow .

public static ObservableCollection<State> BindState { get; set; } *** Look we use Static in here

 

public DataBind()

{

BindState = Details.GetStatename();

}

    5.  Now , in xaml page last code for the StateCombobox.

<ComboBox

DisplayMemberPath="Statename" Height="23"

HorizontalAlignment="Left"

ItemsSource="{Binding Statename}"

Margin="11,3,0,0" Name="StatecomboBox"

VerticalAlignment="Top" Width="189"

Grid.Column="1" Grid.Row="6" />

    6. U think that only last task is left in the codebehind page just bind the Combbobox with ViewModel Property . if u will do that now u get the names of the State but the main purpose of our this task will not fulfilled.u will see the all names of the States from  “Tripura”,”Assam”…..to “Chattagram.” But we don’t need that we need the Country wise states if u select India then u will see the only Indian States. If u Select Pakistan then u will see that Country’s corresponding states. SO here is the main use of our foreign Key.

     7.   So for that we need to write Some one Step more Code. But not very Complex. Just Follow.
In the ViewModel DataBind.cs we will write one Method That will compare the StateId with CountryId & then filter the States like that.

public List<State> GetStatenamebyId(int CountryId) <------------------See the parameter

{

List<State> filterstate = new List<State>();

foreach (State item in DataBind.BindState)

{

if (item.StateId == CountryId) ?--------------------------Here Comparing with CoutryId with StateId

{

filterstate.Add(new State { StateId = item.StateId, Statename = item.Statename });

}

}

return filterstate;

}

For that u will also need to write one namespace using System.Colloctions.Generic; For here we use List.

    8. Now , in the CodeBehind  of the MainApplication.xaml page we need to bind this viewmodel method with State Combobox only in the SelectionChanged of the CountryComboBox. So the Final Code is here:

private void CountryComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

int i = ((Country)e.AddedItems[0]).StateId;

this.StatecomboBox.ItemsSource = d.GetStatenamebyId(i);

}

So, this is the Pic-6  ur task:

         pic – 6

Conclusion

So , its upto now its all . Hope ,u enjoy this.

I am beginner in Silverlight . Since last 7 Months I’m doing working(learning) Silverlight. I love it . I do lots of mistake also . But in this article I tried my best to make it  properly Useful. After  all any suggestion, Any mistake , or any technical feedback  are most welcome . This will improve my Skill & myself. U all experienced people can also develop it with lots of modifications. Pl let me know so that I can get some knowledge from u. The main logically idea I find out for this article from the Pdsa site Which I mentioned in the Top of the Article. 

Page copy protected against web site content infringement by Copyscape

About the Author

debal_saha-9451
Full Name: DEBAL SAHA
Member Level: Starter
Member Status: Member
Member Since: 3/15/2011 4:01:43 AM
Country: India

http://silverlightpractice.blogspot.com/

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)