Wednesday, 11 February 2015

ComboBox in Datagridview

How to fill ComboBox in Datagridview in vb.net

I have added a combo box in a specific column in the grid and i have populated it. So when the grid is filled the combo box are also filled with predefined values.

1. Write the code at .vb page

  Dim sql As String

        sql = "select * from color_mas"
        Dim dt As DataTable
        dt = DataTable(sql)
     
        If dt.Rows.Count > 0 Then

            'For j As Integer = 0 To dt.Rows.Count - 1

            Dim col As New DataGridViewComboBoxColumn
            col.DataPropertyName = "Color Name"
            col.HeaderText = "Colorname"
            col.Name = "Colorid"

            col.DataSource = dt
            col.DisplayMember = "Colorname"
            col.ValueMember = "Colorid"
            DataGridView1.Columns.Insert(0, col)

        End If

2. After Add control add filled look like this



How to Bind Data to ComboBox from Database in Windows Form

How to Bind Data to ComboBox from Database in Windows Form  C#.Net.



Step1 :
 
First you need to design a table in Sql Database to retrieve the Data from database.
 

Step2:
 
 click New Project. Select Windows Forms Application as your project type.
 
Design the Form using controls taken from Toolbox.
  
Step3: 
Now open the Form.cs page and write the following source code.

Form.cs Code :

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;
using System.Data.SqlClient;

namespace combox_binding
{
    public partial class Form1 : Form
    {
        SqlConnection con = new SqlConnection("Data Source=Manish;Initial 
Catalog=demo;User ID=sa;Password=server");
        public Form1()
        {
            InitializeComponent();
            bind();
        }

        private void bind()
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter("Select stuID,stuname 
              from student", con);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataRow dr;
            dr = dt.NewRow();
            dr.ItemArray = new object[] { 0, "---Select an Name---" };
            dt.Rows.InsertAt(dr, 0);
            comboBox1.DisplayMember = "stuname";
            comboBox1.ValueMember = "stuID";
            comboBox1.DataSource = dt;
            con.Close();
        }

    }
}



Step4:
Now build the Solution and Debug it for the output.


Tuesday, 10 February 2015

How to show data in a nested DataGrid using C# Windows Forms



Here I will describe how to show data in a nested DataGrid using C# Windows Forms.


This is applicable to those cases where we need to display master and child data/ rows.


  • The following describes adding a Datagrid control in Windows Forms.
  • As in the screen below we can add a datagrid to Windows Forms.
  • Right-click in the toolbar then choose item.


After add the datagrid control and work.


1.C# Code:

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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Parent table
            DataTable dtstudent = new DataTable();
            // add column to datatable  
            dtstudent.Columns.Add("Student_ID", typeof(int));
            dtstudent.Columns.Add("Student_Name", typeof(string));
            dtstudent.Columns.Add("Student_RollNo", typeof(string));
            //Child table
            DataTable dtstudentMarks = new DataTable();
            dtstudentMarks.Columns.Add("Student_ID", typeof(int));
            dtstudentMarks.Columns.Add("Subject_ID", typeof(int));
            dtstudentMarks.Columns.Add("Subject_Name", typeof(string));
            dtstudentMarks.Columns.Add("Marks", typeof(int));
            //Adding Rows

            dtstudent.Rows.Add(1, "Manish", "2001");
            dtstudent.Rows.Add(2, "Ram   ", "2002");
            dtstudent.Rows.Add(3, "Ajay Ji", "2003");
            dtstudent.Rows.Add(4, "NIKHIL", "2004");
            // data for devesh ID=111
            dtstudentMarks.Rows.Add(1, "01", "DBMS", 99);
            dtstudentMarks.Rows.Add(1, "02", "ASP.NET", 77);
            dtstudentMarks.Rows.Add(1, "03", "C#", 100);
            dtstudentMarks.Rows.Add(1, "01", "VB", 99);
            //data for ROLI ID=222
            dtstudentMarks.Rows.Add(2, "01", "DBMS", 80);
            dtstudentMarks.Rows.Add(2, "02", "ASP.NET", 95);
            dtstudentMarks.Rows.Add(2, "03", "C#", 95);
            dtstudentMarks.Rows.Add(2, "01", "VB", 99);

            DataSet dsDataset = new DataSet();
            //Add two DataTables  in Dataset

            dsDataset.Tables.Add(dtstudent);
            dsDataset.Tables.Add(dtstudentMarks);
            DataRelation Datatablerelation = new DataRelation("DetailsMarks", dsDataset.Tables[0].Columns[0], dsDataset.Tables[1].Columns[0], true);
            dsDataset.Relations.Add(Datatablerelation);
            dataGrid1.DataSource = dsDataset.Tables[0];  
        }
    }
}


2. Figure like this

We will get the following screen having expandable rows in the DataGrid.




3. After Click Details datgrid show like this




Keep It Up.

Monday, 9 February 2015

Populated the DataGridView in C# in Window Application

 

How To Fill DataGridView in window application with c#

DataGridView displays data from SQL databases. This tutorial takes a specific table from a database and display it on a DataGridView. This is done with a DataAdapter and data logic. A visual representation of data is the end result.


C# Code Write Like this

  1. Add the DataGridView control from toolbox in C# window  Form
  2. Add the allconnection class in project ,which defined the all needed public functions there.


Allconnection Class code here


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Design;
using System.Drawing.Printing;


/// <summary>
/// Summary description for DataUtility
/// </summary>

using class AllConnection
{
    # region All Module level variables
    SqlDataAdapter Da;
    public SqlConnection cnn;
    SqlCommand Cmd;
    DataSet ds;

    # endregion

    public void ConnectServer()
    {
        if (cnn == null)
        {

            cnn = new SqlConnection("Data Source=.;Initial Catalog=Hotel;Persist Security Info=True;User ID=sa;Password=server");
          
        }       

        if (cnn.State == ConnectionState.Closed)
        {
            cnn.Open();
        }

        Cmd = new SqlCommand();
        
        Cmd.Connection = cnn;        
    }
    public void CloseConnection()
    {
        if (cnn.State == ConnectionState.Open)
        {
            cnn.Close();
        }
    }
    /// <summary>
    /// This is to release the memory from the connection object
    /// </summary>
    public void DisposeConnection()
    {
        if (cnn != null)
        {
            cnn.Dispose();
            cnn = null;
        }
    }
    public int ExecuteSql(String Sql)
    {
        ConnectServer();
        //int Result;
        //Set command object properties

        Cmd.CommandType = CommandType.Text;
        Cmd.CommandText = Sql;
        Cmd.CommandTimeout = 3000;

        // Now call the method

        int Result = Cmd.ExecuteNonQuery();

        CloseConnection();
        DisposeConnection();

        return Result;
    }
    public bool IsExist(string sql)
    {

        ConnectServer();
        //now set command object properties
        Cmd.CommandType = CommandType.Text;
        Cmd.CommandText = sql;
        Cmd.CommandTimeout = 2000;

        //Execute Command object method
        int Result = (int)Cmd.ExecuteScalar();


        CloseConnection();
        DisposeConnection();

        if (Result > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public SqlDataReader GetDataReader(String Sql)
    {
        ConnectServer();
        SqlDataReader dReader;
        Cmd.CommandType = CommandType.Text;
        Cmd.CommandText = Sql;
        Cmd.CommandTimeout = 1000;

        dReader = Cmd.ExecuteReader();
        //CommandBehavior.CloseConnection
        return dReader;
    }
    public void charonly(KeyPressEventArgs e)
    {
        if (Char.IsNumber(e.KeyChar) || Char.IsSymbol(e.KeyChar) || Char.IsWhiteSpace(e.KeyChar) || Char.IsPunctuation(e.KeyChar))
        {
            MessageBox.Show("Only Char are allowed");
            e.Handled = true;
        }
    }
    public void charAndDigit(KeyPressEventArgs e)
    {
        if (e.KeyChar != 39)
        {
            e.Handled = false;
        }
        else
        {
            MessageBox.Show("Invalid Input");
            e.Handled = true;
        }
    }
    public void UpperCase(KeyPressEventArgs e)
    {
        try
        {
            e.KeyChar = Char.ToUpper(e.KeyChar);
        }
        catch { }
    }

    public void digitonly(KeyPressEventArgs e)
    {
        try
        {
            if (!(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar)))
            {
                e.Handled = true;
                MessageBox.Show("Enter only digit point.", "Alert!");
            }
        }
        catch { }
    }
    public void digitAndDeclmal(KeyPressEventArgs e)
    {
        try
        {
            if (!(char.IsDigit(e.KeyChar) || char.IsControl(e.KeyChar) || char.IsPunctuation(e.KeyChar)))
            {
                e.Handled = true;
                MessageBox.Show("Enter only digit and decimal point.", "Alert!");
            }
        }
        catch { }
    }
    public DataTable GetDataTable(String sql)
    {
        DataTable dt = new DataTable();
        try
        {
            ConnectServer();
           

            Da = new SqlDataAdapter();
            Cmd.CommandType = CommandType.Text;
            Cmd.CommandText = sql;
            Cmd.CommandTimeout = 2000;

            Da.SelectCommand = Cmd;
            //ds = new DataSet();
            Da.Fill(dt);
            //dt = ds.Tables["table"];
            CloseConnection();
            return dt;
        }
        catch
        {
            return dt;
        }
    }
    public DataTable returnDataTable(string sql)
    {
        //Con.Open();
        ds = new DataSet();
        Da = new SqlDataAdapter(sql, cnn);
        Da.Fill(ds, "datatable");
        DataTable dt = new DataTable();
        dt = ds.Tables["datatable"];
        cnn.Close();
        return (dt);
    }
  
    public void FillCombo(string Query, string datatext,string datavalue, ComboBox ComboBox1)
    {
        try
        {
            ConnectServer();
            ComboBox1.Items.Clear();
            ComboBox1.Text = "";
            SqlCommand cmd = new SqlCommand(Query,cnn);
            SqlDataAdapter ada = new SqlDataAdapter(cmd);
            //SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            ada.Fill(dt);
            //while (dr.Read())
            //{
            //    ComboBox1.Items.Add(dr[0].ToString());
            //}
            ComboBox1.DataSource = dt;
            ComboBox1.DisplayMember =datavalue ;
            ComboBox1.ValueMember = datatext;
           // dr.Close(); 
            CloseConnection();
            DisposeConnection();
        }
        catch (Exception)
        {
          //  throw;
        }
    }
    public void FillList(string Query, ListBox ListBox1)
    {
        ListBox1.Items.Clear();
        ConnectServer();
        SqlCommand cmd = new SqlCommand(Query, cnn);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            ListBox1.Items.Add(dr[0].ToString());
        }
        dr.Close();
        CloseConnection();
        DisposeConnection();
    }
    public void FillDataGridView(string Query, DataGridView DataGridView1)
    {
       
        ConnectServer();
        SqlCommand cmd = new SqlCommand(Query, cnn);
        SqlDataAdapter ada = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        ada.Fill(ds, "man");
        DataGridView1.DataSource = ds;
        DataGridView1.DataMember = "man";
        CloseConnection();
        DisposeConnection();
    }
    public void FillLabel(string Query, Label Label1)
    {
        ConnectServer();
        Label1.Text = "";
        SqlCommand cmd = new SqlCommand(Query, cnn);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            Label1.Text = dr[0].ToString();
        }
        dr.Close();
        CloseConnection();
        DisposeConnection();
    }
    public void FillTextBox(string Query, TextBox TextBox1)
    {
        ConnectServer();
        TextBox1.Text = "";
        SqlCommand cmd = new SqlCommand(Query, cnn);
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            TextBox1.Text = dr[0].ToString();
        }
        dr.Close();
        CloseConnection();
        DisposeConnection();
    }

  public void tb_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar)&& !char.IsDigit(e.KeyChar)&& e.KeyChar != '.')
        {
            e.Handled = true;
        }

        // only allow one decimal point
        if (e.KeyChar == '.'
            && (sender as TextBox).Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }
    }

}

3. C sharp code write at the form1.cs file


Form1.CS Code like this:

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;
using System.Data.SqlClient;

namespace VisualStudioExpert_Demo
{
    
    public partial class Form1 : Form
    {
        AllConnection dut = new AllConnection();
       string sql="";
public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { sql ="select BillNo,RoomNo,CustomerName,CustomerAdd,CustomerMob,Total
           from BillingMaster";
          DataTable dt=  dut.GetDataTable(sql);
            if (dt.Rows.Count>0)
            {
                dataGridView1.DataSource = dt;
                
            }
        }
    }
}


Now After fill the datagridview look like this figure:




Thursday, 5 February 2015

How to show the record using DetailsView in ASP.NET


How to show the record using DetailsView in ASP.NET


To show complete details about a record, we can use DetailsView control


In the  .aspx page we have a DetailsView control of ASP .Net  with AutoGenerateColumns true and other with false. The first DetailsView displays all the default columns from the datasource automatically and 2nd one let us define our structure and style of the data to display.

<asp:DetailsView ID="DetailsVw1" runat="server" AutoGenerateRows="true" />



 <hr />DetailsView with custom Value
        <asp:DetailsView ID="DetailsVw2" runat="server" AutoGenerateRows="false">
            <Fields>                
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Father Name" DataField="FatherName" />
                <asp:BoundField HeaderText="Age" DataField="Age" />
                <asp:BoundField HeaderText="Mobile" DataField="Mobile" />
            </Fields>
        </asp:DetailsView>

In the .CS code, I have used ADO.NET to Get the data from the database and specified the data source to the DetailsView control.
string Connectionstr= ConfigurationManager.ConnectionStrings["Manishconnection"].ConnectionString;
 protected void Page_Load(object sender, EventArgs e)
 {

if (!IsPostBack)
 {
  FillData();
  }
 }
private void FillData()
  {
   DataTable dt= new DataTable();

  // get the connection

 using (SqlConnection con = new SqlConnection(Connectionstr))
  {
  // write the sql statement to execute
    string sql = "SELECT AutoId, Name, FatherName, Age, mobile FROM
    ManishDetail ORDER By Id";
    // instantiate the command object to fire
  using (SqlCommand cmd = new SqlCommand(sql, con))
     { 
        // get the adapter object and attach the command object to it
       using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
        {
  // fire Fill method to fetch the data and fill into DataTable
        ad.Fill(dt);
        }
       }
    }

 // specify the data source for the DetailsView

 DetailsVw1.DataSource = dt;// bind the data now

    DetailsVw1.DataBind(); DetailsVw2.DataSource = dt; DetailsVw2.DataBind();
    }




We have kept AutoGeneratedRows property of the first DetailsView to true (by default it has true value) so several rows corresponding to each columns of the data source will be created. The 2nd DetailsView takes of the fields specified with their header and footer specified in the asp:BoundField and asp:TemplateField and displays the record.

Wednesday, 4 February 2015

Merge Array

How To Merge two array

T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
int array1OriginalLength = array1.Length;
Array.Resize(ref array1, array1OriginalLength + array2.Length);
Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length);

Merge Two DataBase


How To Merge Multiple Access database into one database in c# Window Application


I suggest you take the following steps:
  1. Create a database with a single table to hold the final results. The table should have the exact same structure as the individual files, but with a primary key field - either the path to the database file, or some other unique value for each row (this can be generated with an AutoNumber field). You may want an additional column for the database path in any case, particularly if you need to prevent rereading the same database file multiple times.
  2. Open an ADO.NET connection to the final database, using the OleDb provider. This entails a) creating an OleDbConnection object, b) creating an OleDbCommand object that runs on the connection, c) setting the CommandText of the command object to an SQL statement, and d) executing the command.
  3. Your SQL statement could look something like this:
    INSERT INTO desttable (pkfield, field1, field2 ...)
    SELECT field1
    , field2
    FROM sourcetable
    sourcetable can also be a table in a different database like so:
    INSERT INTO desttable (pkfield, field1, field2 ...)
    SELECT field1
    , field2
    FROM sourcetable IN path\to\mdb
    so for each path you could build the SQL statemnt by substituting the appropriate path each time.
  4. If you want to iterate over all the mdb files in a particular folder, you can use the EnumerateFilesmethod of the Directory class, in the System.IO namespace. Alternatively, you can open up a dialog box with the OpenFileDialog in the Windows.Forms namespace.
  5. Once you've figured out what kind of UI you want to see, it should be trivial to bind to this data.

Working with 3- Tier Architecture in C#

  Introduction In this article we will learn Use to 3- Tier architecture in C#.NET application. 3-Tier architecture is very famous and ...