-->

Friday, June 6, 2014

How to populate comboBox in windows form c#

ComboBox is a collection, in which we can take Text as well as value of the text. After array, developer designed comboBox or DropDownList because array contains one attribute of object, its does not take two value at a time. Suppose you want to store employee name and age into memory. Where we would not use array. Here we will bind the comboBox in different manner like
Method-1 : Bind ComboBox from dataset and datatable using ADO.NET
Method-2 : Bind ComboBox using Entity framework.

Method-1

I have a database table like Students, which take some value. The Data View of table, which is stored in database.

C# Code for binding ComboBox (Binding from DataReader)

using System;
using WindowsFormsApplication10;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Entity;
using System.Data.SqlClient;

namespace WindowsFormsApplication10
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=(LocalDB)\\v11.0; Initial Catalog=STUDENTer; Integrated Security=true";
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "select * from Students";
            cmd.Connection = con;
            SqlDataReader rd = cmd.ExecuteReader();
            while (rd.Read ())
            {
                string name = rd.GetString(1);
                comboBox1.Items.Add(name);

            }

        }
    }
}

Binding from DataTable

 private void Form1_Load(object sender, EventArgs e)
        {
           
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=(LocalDB)\\v11.0; Initial Catalog=STUDENTer; Integrated Security=true";
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "select * from Students";
            cmd.Connection = con;
            SqlDataReader rd = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(rd);
            comboBox1.DataSource = dt;
            comboBox1.DisplayMember = "name";

        }

Binding from DataSet

 private void Form1_Load(object sender, EventArgs e)
        {
           
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=(LocalDB)\\v11.0; Initial Catalog=STUDENTer; Integrated Security=true";
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "select * from Students";
            cmd.Connection = con;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            comboBox1.DataSource = ds.Tables[0];
            comboBox1.DisplayMember = "name";

        }

Method-2

If you want to bind combobox using entity framework or you can say strong model binding, just follow my steps.
Step-1 : One class, which name as "Student.cs", which works as database table.

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

namespace WindowsFormsApplication10
{
   public class Student
    {
        public int Id { get; set; }
        public string name { get; set; }
    }
}
In this class we are taking two member first is Id and second is name.
Step-2 : Take another class, which name as "DataContext", which is used for creating database also used for inserting table in it. Look like

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

namespace WindowsFormsApplication10
{
    class DataContext: DbContext
    {
        public DataContext() :
            base("connectionstring1")
        {
           

        }
        public DbSet<Student> Students { get; set; }

    }
}
In this code, DataContext class inherited from DbContext class. Base class constructor create database using conectionstring, which is defined in App.Config file. like

<connectionStrings>
    <add name="connectionstring1" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0; Initial Catalog=STUDENTer; Integrated Security=true" />
  </connectionStrings>

Step-3 : Add ComboBox control on form
Step-4 : Copy this code and paste into your form load event
private void Form1_Load(object sender, EventArgs e)
        {
            DataContext dc=new DataContext();
            var stu = from student in dc.Students
                      select new
                      {
                         student.name
                      };
            comboBox1.DataSource = stu.ToList();
            comboBox1.DisplayMember = "name";

        }

Code Generate the following output

How to populate comboBox in windows form c#

Thursday, June 5, 2014

How to use font dialog in winforms c#

Font dialog is used for changing the font style of the text. In font style there are many attributes available like font face, font color, font size etc. Now, if you want to use font dialog in windows form then simple drag a font dialog control from the tool box and drop into your form page also set some required properties , OK lets take an simple example, in this we take some control on windows form and change their font attribute through font dialog. follow my steps for using font dialog control.



Step-1 : Add one rich textBox and Button control on the form.
Step-2 : Raise click event on button control.
Step-3 : Copy this code and paste into your button control event handler.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication11
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FontDialog ftdlg = new FontDialog();
            ftdlg.ShowColor = true;
            if (ftdlg.ShowDialog ()==DialogResult.OK & !String.IsNullOrEmpty(richTextBox1.Text))
            {
                richTextBox1.SelectionFont = ftdlg.Font;
                richTextBox1.SelectionColor = ftdlg.Color;
            }
        }
    }
}

Now code generate the following output












In this example, first line in event handler define, first to create instance of font dialog, font dialog control doesn't show color in it bydefault so you can change property of it using set ShowColor is true, which is define in second line. In third line we are checking that font dialog is open also return true, when we press OK button. 
Note : Third line also check that 'text' must be selected in rich textBox
 After setting the attribute you can assign attribute to selected text, which is define in fifth and sixth line in the code

Wednesday, June 4, 2014

Return Text Input Element using Html.TextBox() handler: MVC

Html.TextBox() handler used to return text input element on the page at run time. It supports some types of parameters discussed and also have some more options to returning text inputs on the page. Mostly it is of two types listed below with their specification and uses.

@Html.TextBox(Parameter collection...)

This html handler is used to return text input element to be input some values by user like name, age, address and more. As this element is used like a method in Asp.Net MVC, this may have some parameters to be passed with it. This handler returns only an input field in the form of

<input type="text" name="name" id="id" />

Following is list of parameters this handler may used:
  • Name: used to specify name of form field (can be used to find control on page) and this parameter is of string type.
  • Value: this parameter is of type object and used to specify value of text input element. If this value is null then this element will get the value from viewdata dictionary otherwise model data dictionary.
  • Format: used to format the input value in prescribed format string. To format the text input in date form, programmer may use "{0:d}"
  • Html Attributes: the object contains html attributes to set for the element like class, font size and many more attributes.
    @Html.TextBox("txtName", "Student Name", "{0:d}", new { @class = "txtClass" })

@Html.TextBoxFor(Parameter collection...)

The main difference between @Html.TextBox() and @Html.TextBoxFor() is this handler use prediction to resolve the value to be shown. All the remaining parameters are same in both the handlers.

This method is used when programmer binds this page through a model class (having some properties). Programmer can specify more html attributes within the related section.

For example the following line of code will fix the max length of textbox
@Html.TextBoxFor(m=>m.Name, new { maxlength = "20" })

To disabled the textbox just specify the disabled attribute like written below:
@Html.TextBoxFor(m=>m.Name, new { disabled = "disabled" })

Return Label Element using Html.Label() Handler: MVC

Html.Label() handler used to return label element on the page at run time. It supports some types of parameters discussed and also have some more options to returning labels on the page. Mostly it is of three types listed below with their specification and uses.

Html.Label(parameter collection...)

This Html handler is used to return label element with property name specified by the parameter expression. Here is collection of parameter this html handler used:

  • Expression: used to identify the property to display.
  • label text: specify the text of label to display.
  • Html Attributes: this parameter is type of object, contains all the elements to be set for this label element.
    @Html.Label("stName", "Student Name", new { @class = "lblClass" })

Html.LabelFor(parameter collection...)

This handler is used for showing the label element of property passed from the model, the page bind. For example the page is bind to student model and we bind this handler with student name then this handler will show the name of student like shown below:

@Html.LabelFor(model => model.Name)
Here model represent the class name passed to bind this view. This parameter must be defined in prediction type as shown in the above code, without prediction it will show an error. Remaining parameters are same as Html.Label() handler.

@Html.LabelForModel(parameter collection...)

This handler returns a label whose for value is that of the parameter represented by the model object. It is mostly used in editor templates in MVC View. e.g.

@Html.LabelForModel() - it shows the label element for the string property of model bind with this view.

Variable, Conditions and Looping in Asp.Net Razor: C#

Like all other programming languages, variables are named entities used to store data to be used in particular scope. Declaration of variables must follow all the rules described in other languages like must begin with alphabetic character, cannot contain white spaces or any reserved character.

Variables can be declared by their specific data type or "var" keyword. Variables may use all the operators as other languages use. Following lines of code will declare some variables of different data types:

// Variables having var datatype
var name = "Computer Programming"
var url = "dotprogramming.blogspot.com"
var authors = 10
var estb = 2013

//Datatypes accordingly
String name = "Computer Programming"
String url = "dotprogramming.blogspot.com"
int authors = 10
DateTime estb = 2013

Razor syntax also supports conditional expressions i.e. if...else statement to be used some lines of code accordingly. Following lines of code will specify an if...else code block which with always show the true case, because of the condition.

@{ if (true)
   {<p>This is true case</p>}
   else
   {<p>This is false case</p>}
}

By using above type of code, programmer can easily specify the divisions on individual condition. Like this conditional statement razor also supports looping statements i.e. For loop, for-each loop, while loop etc. To be execute some lines of code multiple times programmer need to use these looping constructs.

Following line of code will write the string ("dotprogramming.blogspot.com") 10 times on the page:

@{ for (int i = 0; i < 10; i++)
   {
       <p><a href="https://dotprogramming.blogspot.com">Computer Programming @(i+1) </a></p>
    
   }
}

Running these line of code will show you 10 links of the same url (as specified):

Variable, Conditions and Looping in Asp.Net Razor: C#

Generating same output from for-each loop, programmer need to write something like these lines of code:

int[] array = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

foreach (var item in array)
{
   <p><a href="https://dotprogramming.blogspot.com">Computer Programming @(item) </a></p>
}

Introduction to Mark-Up Language: Asp.Net Razor

Razor, mostly used language in Asp.Net MVC, is not a programming language but it is a server-side mark up language. It is basically used to let the programmer embed server based code in to web pages.

By running on the server-side, Razor code can perform complex tasks including database accessing. Server executes this code inside the page before returning to the browser at the time of calling a particular page. The main advantage of this markup language is, it supports c sharp (C#) as well as visual basic (VB).

Here are some rules/instructions to be follow when writing razor language with c#:

  • Declarations of variables/functions will start with @
  • Code blocks are enclosed in @ {... }
  • Statements will end with semicolon (;)
  • Remember c# code is case sensitive
  • Comments can be written within @* ...... *@

Following line of code will explain you a brief knowledge about razor syntaxes:

@* Commented Section
Below are some line of code which will use two variables declared in razor and then use them to show title and description of the page.
*@

@{
    var title = "This is this page's title";
    var description = "The description about this page";
}

<div>
    <p>Title: @title</p>
    <p>Description: @description</p>
</div>

<!-- Comments can also be written like this -->

The first block of code is used for commented lines as written as heading. Second block is used to declare two array i.e. title and description that can be used further in the code. The last code is html code and simple div and p tag are placed there to write the values of above declared variables.

Razor provides mostly all the server-side objects with all these methods they can have. To show current date/time razor syntax will be:

<p>
    Today Date:  @DateTime.Today 
    Time:  @DateTime.Now.TimeOfDay
</p>

There are many more we have to learn about razor syntax like variables, conditional statements, looping constructs etc.

Types of Secondary XML Indexes in SQL Server

These are non-clustered index of the primary XML index. There must be a primary xml index before each secondary xml index. Following are some types of secondary xml indexes:

Path Indexes

The path index is built on the path value columns of the primary XML indexes. This index improves the performance of queries that use paths and values to select data.

For example, if you execute a query that checks for the existence of a product model ID using an XQuery expression as /PD:ProductDescription/@ProductModelID[.=”19”], you can create a path secondary index on the CatalogDescription column of the ProductModel table. In this path index, you can use the primary index created previously.

The following statement creates a Path index on the CatalogDescription column:

CREATE XML INDEX PIdx_ProductModel_CatalogDescription_PATH ON Production.ProductModel (CatalogDesctiption)USING XML INDEX PXML_ProductModel_CatalogDescription FOR PATH

The preceding code create a path index, Pldx_ProductModel_CatalogDesctiption_PATH

Value Indexes

The value indexes contain the same items as path indexes but in the reverse order. It contains the value of the column first and then the path id. This index improves the performance of queries that use paths to select data.

For example, if you execute a query that checks the existence of a node in an XQuery expression such as//Item@ProductID=”1”], you can create a value secondary index by using the primary index created previously.

The following statement creates a value index on the CatalogDesctiption column:

CREATE XML INDEX PIdx_ProductModel_CatalogDesctiption_VALUE ON Production.ProductModel (CatalogDesctiption)
USING XML INDEX PXML_ProductModel_CatalogDescription
FOR VALUE

The preceding code creates a value index,
PIdx_ProductModel_CatalogDescription_VALUE on the CatalogDescription column of the table.

Property Indexes

The property index contains the primary key of the base table, path id, and the clause columns of primary XML indexes. This index improves the performance of queries that use paths to select data.

For example, if you execute a query that returns a value of the node in an XQuery expression, such as /ItemList/Item/@ProductID)[1], you can create a property secondary index on the CatalogDescription column of the ProductModel table by using the following statement:

CREATE XML INDEX PIdx_ProductModel_CatalogDescription_PROPERTY ON Production.ProductModel (CatalogDescription)
USING XML INDEX PXML_ProductModel_CatalogDescription FOR PROPERTY

The preceding code creates a property index, PIdx_ProductModel_CatalogDescription_PROPERTY, on the CatalogDescription column of the table.

You need to consider the following guidelines while creating an XML index:

  • XML indexes can be created only on XML columns.
  • XML indexes only support indexing a single XML column.
  • XML indexes can only be added to tables, views, table-valued variables with XML column or XML variables.
  • XML indexes created on a table do not allow you to modify the primary key. To do so, you first need to drop all the XML indexes on the table.
© Copyright 2013 Computer Programming | All Right Reserved