Showing posts sorted by date for query sql. Sort by relevance Show all posts
Showing posts sorted by date for query sql. Sort by relevance Show all posts

Wednesday 21 May 2014

How to use mysql database in csharp

INTRODUCTION


In this article i am going to show how to connect a csharp database with mysql database and how to perform basic operations like inserting record in database , delete a specific record from database , updating a specific record and viewing all data and binding the data to datagridview . Mostly with Csharp Applications you have used MSSQL database but we can also use mysql database for this purpose
DOWNLOAD MYSQL WITH CSHARP APP


REQUIREMENTS

  • Visual Studio 2010 or Visual Studio 2012 
  • MYSQL Database installed with admin roles
  • Dot/connector connec

WHAT WE ARE GOING TO COVER


In this Article we are going to cover the following points
  1. Connect Csharp with mysql
  2. Insert data in mysql database with Csharp code
  3. Delete data in mysql database with Csharp code
  4. Update data in mysql database with Csharp code
  5. Select data in mysql database with Csharp code

CREATING DATABASE


First of Start your Wamp server or Xamp server services This will start Phpmyadmin where all database or SQL related work will be done . Phpmyadmin will be used for create new database schemas and other database oprations are done.

  • Start Wamp / xampp server

How to use mysql database in csharp
  • Then Click on phpMyAdmin as shown in Image above .
  • Now you will get a screen like the image below

    How to use mysql database in csharp
  • If you are using default password for Phpmyadmin then directly click on Go button . Then you will get a screen like below 
  • Then click on Databases as shown in image below to create a new database that will be required for this Application
    How to use mysql database in csharp
  • Then you will get window as shown below Fill up the Database name and Click on Create button
    How to use mysql database in csharp
  • After database is created Now Run the database script we have provided in this tutorial in next steps and run this script as shown in image below ........Just go to sql Tab and paste full script there.

    How to use mysql database in csharp
    • Remember one thing use same name of database as i have given in the snapshot

    DOWNLOAD DATABASE SCRIPT FILE

    Database Script File

    DOWNLOAD FULL PROJECT WITH CODE

    Download Complete project How to use mysql database in csharp

    DOWNLOAD MYSQL CONNECTOR DLL's FOR DOTNET

    For connecting Mysql with Csharp in dotnet you must have connector . you require Connector/NET for mysql connectivity with csharp . you can download Mysql connector / Net from link below :-

    Download Dotnet connector for mysql and csharp


    HOW TO USE MYSQL DLL's

    STEPS :- 

    • Right Click on Solution Name
    • In pop-up menu click on Add Reference
      How to use mysql database in csharp
    • Now select Mysql.Data and Click ok
      How to use mysql database in csharp
    • you can also browse for dll downloaded from Browse Tab
      How to use mysql database in csharp
    • Now MySQL.Data dll file will be added successfully to solution .

    INSERT RECORD IN MYSQL DATABASE USING CSHARP CODE


    How to use mysql database in csharp
    CODE :-
      con.Open();
                MySqlCommand cmd = new MySqlCommand("insert into table1(name,branch,phone) values(@name,@branch,@phone)", con);
                cmd.Parameters.AddWithValue("@name", textBox1.Text);
                cmd.Parameters.AddWithValue("@branch", textBox2.Text);
                cmd.Parameters.AddWithValue("@phone", Convert.ToInt32(textBox3.Text));

                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Inserted");

    EXPLANATION :- 
    1. First Connection is opened to mysql connection using connection string
    2. Then Using MySqlCommand class we are passing insert query to mysql database using con object that is used for establishing connection to mysql database
    3. Then @name,@branch,@phone are parameters given to query to dynamically pass data to query
    4. Then parameters are passed to query dynamically using following line of code
      cmd.Parameters.Addwithvalue('parametername' , 'value' );
    5. cmd.ExecuteNonQuery is used to execute the query in cmd object to database 
    6. con.close closes the connection to the database

    DELETE RECORD IN MYSQL DATABASE USING CSHARP CODE                                      


    How to use mysql database in csharp

    CODE :-

    con.Open();
                if (comboBox1.Text != "")
                {
                    MySqlCommand cmd = new MySqlCommand("delete from table1 where id=@id", con);
                    cmd.Parameters.AddWithValue("@id", comboBox1.Text);
                                cmd.ExecuteNonQuery();                                                                                                                   
                                 con.close();


    EXPLANATION :- 

    1. First Connection is opened to mysql connection using connection string
    2. Then Using MySqlCommand class we are passing insert query to mysql database using con object that is used for establishing connection to mysql database
    3. Then @id is parameter given to query to dynamically pass data to query
    4. Then parameters are passed to query dynamically using following line of code
      cmd.Parameters.Addwithvalue('parametername' , 'value' );
    5. cmd.ExecuteNonQuery is used to execute the query in cmd object to database 
    6. con.close closes the connection to the database

    UPDATE RECORD IN MYSQL DATABASE USING CSHARP CODE


    How to use mysql database in csharp

    CODE :-

     MySqlCommand cmd = new MySqlCommand("update table1 set name=@name,branch=@branch,phone=@phone where id=@id", con);
                cmd.Parameters.AddWithValue("@name",textBox6.Text );
                cmd.Parameters.AddWithValue("@branch",textBox5.Text );
                cmd.Parameters.AddWithValue("@phone",textBox4.Text);
                cmd.Parameters.AddWithValue("@id",comboBox2.Text  );
              
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record Updated");

    EXPLANATION :- 

    1. First Connection is opened to mysql connection using connection string
    2. Then Using MySqlCommand class we are passing insert query to mysql database using con object that is used for establishing connection to mysql database
    3. Then @name,@branch,@phone,@id are parameters given to query to dynamically pass data to query to state which field value are to be replaced
    4. Then parameters are passed to query dynamically using following line of code
      cmd.Parameters.Addwithvalue('parametername' , 'value' );
    5. cmd.ExecuteNonQuery is used to execute the query in cmd object to database 
    6. con.close closes the connection to the database

    SELECT RECORD IN MYSQL DATABASE USING CSHARP CODE


    How to use mysql database in csharp

    CODE :-


     MySqlCommand cmd = new MySqlCommand("select * from table1 where id=@id", con);
                cmd.Parameters.AddWithValue("@id", comboBox2.Text);
                MySqlDataAdapter da = new MySqlDataAdapter();
                da.SelectCommand = cmd;
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    textBox6.Text =dt.Rows [0][1].ToString ();
                        textBox5.Text =dt.Rows [0][2].ToString ();
                        textBox4.Text = dt.Rows[0][3].ToString();
                }


    EXPLANATION :- 

    1. First Connection is opened to mysql connection using connection string
    2. Then Using MySqlCommand class we are passing insert query to mysql database using con object that is used for establishing connection to mysql database
    3. Then @name,@branch,@phone,@id are parameters given to query to dynamically pass data to query to state which field value are to be replaced
    4. Then parameters are passed to query dynamically using following line of code
      cmd.Parameters.Addwithvalue('parametername' , 'value' );
    5. Then we have used MySqlDataAdapter that act as a pipeline between database and csharp app . It takes or select query from csharp application and then make interface or link to database and execute the query in database and get result returned by query executed in database
    6. Then it fill the returned result in placeholder called DataTable that saves data returned from or retrieved from database into tabulated form
    7. Now if (dt.Rows.Count >0) checks if dt contains some item then put the data in respective text fields

    Full Code For Insert update delete and select Data from Mysql in Csharp Application  ( C# )


    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 MySql;
    using MySql.Data;
    using MySql.Data.MySqlClient;

    namespace mysql
    {
        public partial class Form1 : Form
        {
           public  MySqlConnection con = new MySqlConnection("server=localhost;Uid=root;pwd=;Database=sqldotnet");
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                retrieve();
            }
            public void retrieve()
            {

                {
                    MySqlCommand cmdsel = new MySqlCommand("select *  from table1 ", con);
                    MySqlDataAdapter dasel = new MySqlDataAdapter();
                    dasel.SelectCommand = cmdsel;
                    DataTable dtsel = new DataTable();
                    dasel.Fill(dtsel);
                    dataGridView1.DataSource = dtsel;
                }
                {
                    int cnt = comboBox1.Items.Count;
                    for (int counter = 0; counter < cnt; counter++)
                    {
                        comboBox1.Items.RemoveAt(0);
                        comboBox2.Items.RemoveAt(0);
                    }
                }
                MySqlCommand cmd = new MySqlCommand("select id  from table1 ", con);
                MySqlDataAdapter da = new MySqlDataAdapter();
                da.SelectCommand = cmd;
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    int cnt = dt.Rows.Count;
                    for (int counter = 0; counter < cnt; counter++)
                    {
                        comboBox1.Items.Add(dt.Rows[counter][0].ToString());
                        comboBox2.Items.Add(dt.Rows[counter][0].ToString());
                    }
                }
                comboBox1.Text = "";
                comboBox2.Text = "";
            }
       
    //Delete Record
            private void button2_Click_1(object sender, EventArgs e)
            {
                con.Open();
                if (comboBox1.Text != "")
                {
                    MySqlCommand cmd = new MySqlCommand("delete from table1 where id=@id", con);
                    cmd.Parameters.AddWithValue("@id", comboBox1.Text);
                    cmd.ExecuteNonQuery();
                    retrieve();
                }
                MessageBox.Show("Record Deleted");
            }
    //select Data
            private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
            {
                MySqlCommand cmd = new MySqlCommand("select * from table1 where id=@id", con);
                cmd.Parameters.AddWithValue("@id", comboBox2.Text);
                MySqlDataAdapter da = new MySqlDataAdapter();
                da.SelectCommand = cmd;
                DataTable dt = new DataTable();
                da.Fill(dt);
                if (dt.Rows.Count > 0)
                {
                    textBox6.Text =dt.Rows [0][1].ToString ();
                        textBox5.Text =dt.Rows [0][2].ToString ();
                        textBox4.Text = dt.Rows[0][3].ToString();
                }
            }
    //Update Data
            private void button3_Click_1(object sender, EventArgs e)
            {
                MySqlCommand cmd = new MySqlCommand("update table1 set name=@name,branch=@branch,phone=@phone where id=@id", con);
                cmd.Parameters.AddWithValue("@name",textBox6.Text );
                cmd.Parameters.AddWithValue("@branch",textBox5.Text );
                cmd.Parameters.AddWithValue("@phone",textBox4.Text);
                cmd.Parameters.AddWithValue("@id",comboBox2.Text  );
             
                cmd.ExecuteNonQuery();
                MessageBox.Show("Record Updated");
                retrieve();
            }
    //Insert Data
            private void button1_Click_1(object sender, EventArgs e)
            {
                con.Open();
                MySqlCommand cmd = new MySqlCommand("insert into table1(name,branch,phone) values(@name,@branch,@phone)", con);
                cmd.Parameters.AddWithValue("@name", textBox1.Text);
                cmd.Parameters.AddWithValue("@branch", textBox2.Text);
                cmd.Parameters.AddWithValue("@phone", Convert.ToInt32(textBox3.Text));

                cmd.ExecuteNonQuery();
                con.Close();
                MessageBox.Show("Record Inserted");
                retrieve();
            }
        }
    }


    Wednesday 7 May 2014

    sql insert , Update , delete using c#


    To connect Database from your Windows Application is required  to make Application for querying the database and retrieve the desired result from database . Database in widely used in management software's  and various applications to save record and search the record .

    Database dependent applications are widely used in the market . ERP projects of organisation are highly Database dependent applications . The main two types of databa se that are widely used in .NET Applications :-

    * Microsoft Access Database
    * MSSQL Server ( Microsoft Structured Query Language )


    The main Languages used in .NET Platform for connecting windows application to database are :-

    * C#
    * VB#

    Sql ( Structured Query Language ) is most widely used Database . It is free and Opensource Database . It has simple query structure to Manipulate data from database in Database applications 

    To Learn About SQL and how to learn SQL you can go to following links first then go forward :-

    SQL Tutorial with Examples and snapshots

    insert , update , delete , select queries sql

    Download Database Script file and execute it in your SQL Server

    Steps To Execute this Script file -

    1. Download Script file from link below .

    2. Now open it with MsSql .
    3. Now Create Database Named  'Accounts_database' in MsSql server 
    4. Now select this database from Dropdown 
    5. And Execute the Script code by clicking F5 .

    Design of Form 

    Download Complete Project File


    1. In Design We have some Fields to be filled to insert Data To database

    2. We are having 3 Buttons - One for Update and Insert Operation , Second For Delete Operation and Third for Exit or close form

    3. We are using Datagrid View to Instantly Showing The data in database and it is updated when we insert new data to database or we delete data from database

                                                       Insertion/Updation In Database 


    1. For insertion of data Fill the fields on form Only Code and Agency Name is required and rest of the fields are optional fields


    2. Now you can see filled data is successfully inserted and it is immediately shown in below datagridview


    CODE For Insert/Update


     try


     {
                    SqlCommand cmd1 = new SqlCommand("select * from Agency_detail where  Agency_code=" + textBox1.Text, con);
                    SqlDataAdapter da1 = new SqlDataAdapter();
                    DataTable dt1 = new DataTable();
                    da1.SelectCommand = cmd1;
                    da1.Fill(dt1);
                    if ((dt1.Rows.Count > 0) && (dt1.Rows[0][0].ToString() != ""))
                    {
                        if (MessageBox.Show("ID Already Exist Do you want to Update It", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            SqlCommand cmdupdate = new SqlCommand("update Agency_detail set Agency_Name=@p1,Phone=@p2,fax=@p3,Mobile_Number=@p4,DOJ=@p5,opening=@p6,Remark=@p7,Address=@p8,city=@p9,state=@p10,zip_code=@p11,email=@p12 where Agency_code=" + textBox1.Text, this.con );
                            cmdupdate.Parameters.AddWithValue("@p1", textBox2.Text);
                            cmdupdate.Parameters.AddWithValue("@p2", textBox4.Text);
                            cmdupdate.Parameters.AddWithValue("@p3", textBox3.Text);
                            cmdupdate.Parameters.AddWithValue("@p4", textBox8.Text);
                            cmdupdate.Parameters.AddWithValue("@p5", dateTimePicker1.Value.Date);
                            cmdupdate.Parameters.AddWithValue("@p6", textBox6.Text);
                            cmdupdate.Parameters.AddWithValue("@p7", textBox5.Text);
                            cmdupdate.Parameters.AddWithValue("@p8", textBox17.Text);
                            cmdupdate.Parameters.AddWithValue("@p9", textBox16.Text);
                            cmdupdate.Parameters.AddWithValue("@p10", textBox15.Text);
                            cmdupdate.Parameters.AddWithValue("@p11", textBox14.Text);
                            cmdupdate.Parameters.AddWithValue("@p12", textBox13.Text);

                            //con.con.Open();
                            cmdupdate.ExecuteNonQuery();
                            MessageBox.Show("Updated");
                            retrieve_data();
                            clearall();
                        }
                        else
                        {

                        }
                    }
                    else
                    {

                        if ((textBox1.Text != "") && (textBox2.Text != ""))
                        {
                            SqlCommand cmd = new SqlCommand("insert into Agency_detail values(@para1,@para2,@para3,@para4,@para5,@para6,@para7,@para8,@para9,@para10,@para11,@para12,@para13)", con);
                            cmd.Parameters.AddWithValue("@para1", Convert.ToInt64(textBox1.Text));
                            cmd.Parameters.AddWithValue("@para2", textBox2.Text);
                            cmd.Parameters.AddWithValue("@para3", Convert.ToInt64(textBox4.Text));
                            cmd.Parameters.AddWithValue("@para4", Convert.ToInt64(textBox3.Text));
                            cmd.Parameters.AddWithValue("@para5", Convert.ToInt64(textBox8.Text));
                            cmd.Parameters.AddWithValue("@para6", dateTimePicker1.Value);
                            cmd.Parameters.AddWithValue("@para7", Convert.ToDouble(textBox6.Text));
                            cmd.Parameters.AddWithValue("@para8", textBox5.Text);
                            cmd.Parameters.AddWithValue("@para9", textBox17.Text);
                            cmd.Parameters.AddWithValue("@para10", textBox16.Text);
                            cmd.Parameters.AddWithValue("@para11", textBox15.Text);
                            cmd.Parameters.AddWithValue("@para12", Convert.ToInt64(textBox14.Text));
                            cmd.Parameters.AddWithValue("@para13", textBox13.Text);
                            //con.con.Open();
                            cmd.ExecuteNonQuery();
                            retrieve_data();
                            clearall();
                        }
                        else { MessageBox.Show("Agency ID and Name Must Required"); }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
               



    Deletion Of Data


    To Delete data or  record from database :- 

    1. Enter the Required fields :- ID and Agency Name of Record to be deleted 

    2. Then press delete button and data will be deleted

    3. It will be immediately shown as deleted in datagridview



    CODE For DELETE



     try
                {
                    SqlCommand cmd = new SqlCommand("delete from Agency_detail where Agency_code =@code", this.con);
                    cmd.Parameters.AddWithValue("@code", Convert.ToInt32(textBox1.Text));
                    //con.con.Open();
                    cmd.ExecuteNonQuery();
                    retrieve_data();
                    clearall();
                }
                catch (Exception ex)
                {
                  MessageBox.Show(ex.Message);

                }


    Tuesday 18 March 2014

    Implementing Search Functionality in ASP.NET MVC 4

    What we are Going To cover


    * In this Tutrial we are going to cover how to implement search functionality in Asp.Net MVC 4 . In our web applications in MVC we often need to add the functionality to search the database objects for specific data based on some creteria like to find employees with name starting with 'N' or to find data of employees that have Gender Male

    Download Demo App With Database Link Below

    Creating Database For This Application

    1. First create Database

    * Open Microsoft Sql server . Click on New Query . Now execute the query below to create database

    Create Database searchingInmvc

    Implementing Search Functionality in ASP.NET MVC 4
    Create Database Searching in Asp.net MVC 4

    2. Then Press F5 . This will create Database successfully

    Create Table And Inserting Demo Data


    create table tblEmployee         //creating table
    (
    ID int identity primary key,
    Name nvarchar(50),
    Gender nvarchar(50),
    Email nvarchar(50)
    )
    Implementing Search Functionality in ASP.NET MVC 4
    Creating Table In database 

    //Inserting Demo Data

    Here , we are inserting 4  Rows in Database table

    insert into tblEmployee values('John','Female','john@geeksprogrammings.blogspot.in')
    insert into tblEmployee values('funky','Male','funky@geeksprogrammings.blogspot.in')
    insert into tblEmployee values('wiley','Male','wiley@geeksprogrammings.blogspot.in')
    insert into tblEmployee values('ceren','Female','ceren@geeksprogrammings.blogspot.in')

    Implementing Search Functionality in ASP.NET MVC 4
    Inserting Data in Table 

    Showing All Inserted Data

    Download Database script file

    In link below you can download the script file and then double click on file it will open in sql server . It will create the database automatically for you when you execute it

    Create New MVC 4 Application in Visual Studio

    1. Start Visual Studio with language selected as C#
    2.Click on File --> Then click on New Project
    3. Scroll down and select ASP.NET MVC 4 Web Application

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4


    4. Give appropriate Name,Path and solution Name and Hit Enter
    5. choose Empty Template
    6. Choose Razor View Engine and Hit Enter
    7. Now New MVC 4 web application is started

    Adding Models to MVC 4 Application

    1. In solution Explorer -- > Right click on Models --> Then click on New item

    Implementing Search Functionality in ASP.NET MVC 4

    2. Then select ADO.NET Entity Data Model --.> Give it a valid name like 'sampledatamodel'
    3. Click Add

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4

    4. Now A dialog box appears choose database connection to sql server and give your connection string a name that will be give to connection string in web.config file

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4

    5. click next
    6. Now in next dialog box you will be presented with tables available in database table select you table

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4

    7. Now click Finish
    8. Now Entity model of table is generated you can rename your database here to 'Employee'

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4

    9. Now Model is successfully Added

    Adding Controller and Views To MVC 4 Application

    To add controller to database --

    1. Right click on Controllers folder in solution folder
    2. click on Add --> Then click on Controller

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4

    3. Now Add controller Dialog Box appears
    4. Give your controller a name like 'HomeController'
    5. In template choose  'MVC controller with read/write and views using Entity  Framework'
    6. The Reason behind choosing this is it will automatically generate some pages to insert,delete , update data of model to which we are associating this controller
    7. Now give the Model name that we have added in previous step 'Employee'
    8. Now Choose dbcontext class from dropdown menu and finally  click ADD
    9. This autimatically add Views for insert , update, delete and index view in views folder under controller named folder

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4

     10. Now Run your application . This will give output below:-

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4

    Adding Style And Look To Application

    So we are going to search the database and retrieve data from database and then show the retrieved result to user. For this we have to get some controls and code . The GUI design that are going to give to this application is as below :-

    1. In solution Explorer under Index view Double click on Index.cshtml
    2. Now just before the line '<h2>Index</h2>' add a line 

    <div style='font-family:Arial'>
    and close this div right below the code after table tag 

    Other UpdationAre in Demo Project Downlao And Use it

    3. Update your Index.cshtml file under view folder in solution Explorer with the code below

    @model IEnumerable<SearchInMVC.Models.Employee>
    @{
        ViewBag.Title = "Index";
    }
    <div style="font-family:Arial ">
    <h2>Index</h2>

    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <p>
    @using (Html.BeginForm ("Index","Home",FormMethod.Get ))
    {
    <b>Search by:</b>@Html.RadioButton("searchBy","Name")<text> Name</text>
    @Html.RadioButton("searchBy","Gender")<text>Gender</text><br />
    @Html.TextBox("Search");<input type="submit" value="Search" />
        }
    </p>
    <table border="1">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Gender)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Email)
            </th>
            <th>Action</th>
        </tr>
        @if (Model.Count() == 0)
        {
            <tr>
            <td colspan ="4">No Rows Match Search Criteria</td>
            
            </tr>
        }
        else
        {
    foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Gender)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.ID })
            </td>
        </tr>
    }
        }
    </table>
    </div>




    Now Run your Application and you can see the change with output below :-

    Implementing Search Functionality in ASP.NET MVC 4
    Implementing Search Functionality in Asp.Net MVC 4

    Code Description

    In code above we have used Razor code and instead of using <form> tag that we usually use in html we have used Html Helper below


    @using (Html.BeginForm ("Index","Home",FormMethod.Get ))
    {
    <b>Search by:</b>@Html.RadioButton("searchBy","Name")<text> Name</text>
    @Html.RadioButton("searchBy","Gender")<text>Gender</text><br />
    @Html.TextBox("Search");<input type="submit" value="Search" />
        }




    In Html.BeginForm ("Index","Home",FormMethod.Get )

    Here, Html.BeginForm  is used in place of using form tag . Html.BeginForm  Received 3 arguments .
    Here, "Index" is Name of action that will be executed on posting form  to server
    Here, "Home" is name of controller to which this link will be redirected when clicked
    Here, " FormMethod.Get" type of encoding method that applied on data we are posting 

    Now Open Controller And Add code below to Index Action of home controller

     if (searchby == "Gender")
                {
                    return View(db.Employees.Where(x => x.Gender == search || search ==null).ToList());
                }
                else
                {
                    return View(db.Employees.Where(x => x.Name.StartsWith(search)).ToList());
    }






























    Sunday 26 January 2014

    Error dnndev/desktopmodules/ could not be found

    http://geeksprogrammings.blogspot.com/2014/01/donetnuke.html
    geeksprogrammings.blogspot.in

     DotNetNuke is one of best Web Content Management System Based on Microsoft .Net. The main ease is it's community Edition is OpenSource. After successfull installation of DotnetNuke if you want to develop your own modules for Dotnetnuke .you require following things

    1. Microsoft Visual Studio
    Download Visual Studio 2010

    2. Microsoft Sql Server
    Download SqlServer 2008 32/64 Bit

    3 DotNetNuke C# Compiled Module  OR DotNetNuke Vb# Compiled Module
    DotNetNuke C# / Vb Compiled Module For vs 2010

    First I will recommend if you are using only one website of dotnetnuke at one time one one Host or computer . Put all your website files in C:\inetpub\wwwroot that will be ease not put it in folder in wwwroot as it also works in folder but there could be easy url if you keep them in wwwroot


    Configure Host File

    1. Press windowskey +r from keyboard
    2. In Run dialog Box typein "c:\WINDOWS\system32\drivers\etc" and Hit Enter
    3. Now in New window opened right click on hosts file and open it in your favourite notepad editor
    4. Now put the following line in it and it looks something like in image below
    Put this line :-
    127.0.0.1       dnndev
    5. Save this file and close it
    http://geeksprogrammings.blogspot.com/2014/01/donetnuke.html
    geeksprogrammings.blogspot.in

                          e.g. Hosts file

    6. Now check it its done properly
    7. To check it open any browser Typein- "dnndev/" and Hit enter
    8. if your dotnetnuke site opens then host file configuration done.


    Installation of C# Compiled Module Development 

    1. Download DotNetNuke C# Compiled Module  OR DotNetNuke Vb# Compiled Module
    DotNetNuke C# / Vb Compiled Module For vs 2010

    2. Installing the Visual Studio Template is very straight forward.
    3. First close all instances of VS2008  
    4. Now copy the ZIP file that you downloaded from Codeplex in previous step
    5. Now  paste this ZIP file into a very specific folder.
    6. Open the following folder "My Documents\Visual Studio 2008\Templates folder". 
    7. Within that folder go into ProjectTemplates\Visual C#\
    8. within the Visual C# folder  simply create a new folder Web folder
    9. Place zip file in web folder
    10.  Now open  visual studio 2010 and click on file -> New Project 
    11. christoc.com C# compiled module template give filename and click ok

    ERROR

    The Web Application Project hello is configured to use IIS. The Web server "http://dnndev/desktopmodules/hello/' could not be found."


    Solution

    Now we will do configuration for module development. check Which Version of IIS you are using .Follow the steps below to know which version of IIs you are using

    Steps To Know IIS Version

    1. Press windowskey +r from keyboard
    2. In Run dialog Box typein "inetmgr" and Hit Enter
    3. Now click on Help menu item in Menu Bar
    4. click on About Internet Information Services
    5. This gives version of IIs you are using like in image below
    http://geeksprogrammings.blogspot.com/2014/01/donetnuke.html
    geeksprogrammings.blogspot.in



    6. Now depending on version using steps below


    Configure Bindings In IIS 5

    1. Press windowskey +r from keyboard
    2. In Run dialog Box typein "inetmgr" and Hit Enter
    3. This opens Internet Information Services
    4. Right click on Default WebS ite
    5. click on Properties. This opens Default Website Properties

    http://geeksprogrammings.blogspot.com/2014/01/donetnuke.html

    6. Focus on Web Site Tab under Web Site Identification Section
    7. In this section you see Advance Button after Ip Address Label
    8. click on Advanced Button
    9. It opens Advanced Multiple Web Site configuration window
    11. 10. Now click on Add button under Multiple identities for this Web site
    http://geeksprogrammings.blogspot.com/2014/01/donetnuke.html
    geeksprogrammings.blogspot.in


    12. Put Ip Address field equals to All Unassigned
    13. Put TCP Port equals to 80
    14. Put Host Header Name equals to dnndev
    15. click ok ....again click ok on other window
    16. At last click apply and ok to close properties window


    Configure Bindings In IIS 7

    1. Press windowskey +r from keyboard
    2. In Run dialog Box typein "inetmgr" and Hit Enter
    3. This opens Internet Information Services
    4. In the Connections pane, expand the server name, expand Sites, and then click the Web site on which you want to configure the bindings.
    5. In the Actions pane, click Bindings
    6. In the Site Bindings dialog box, click Add.
    7. In the Add Site Binding dialog box, add the binding information
    to solve dotnetnuke error add binding to iis
    geeksprogrammings.blogspot.in


    8.Put Ip Address field equals to All Unassigned
    9. Put Host Header Name equals to dnndev
    10 click ok

    For any more problem or for Configure Bindings In IIS 7 or other problem you can comment here i am here to help you anytime

    Tuesday 22 October 2013

    Datagridview Cellvaluechanged Event VB.net



    DatagridView is a windows forms grid Control . It was first introduced in 
    .Net framework 1.0 and It comes with advanced and improved features in .Net Framework 2.0  It allows you to show the data in the tabular form. It contains data organized in rows and columns. It can be used to retrieve data in Tabular from from Database . It can be bound to Sql Database or Microsoft-Access Database.


         
    Datagridview Cellvaluechanged Event in VB.net is used to make the change to occur or to call an event when value within particular cell is changed. In this app I have put event on each . when value of cell is changed its corresponding value in Maskedtextbox will change


    Download Datagridview cellvaluechanged App



    Design For Datagridview Cellvaluechanged Event VB.net


    -- Add DatagridView To Form


    1. Click on Tools


    2. Then Scroll down and Find Datagridview .






    3. Now Double click on it to put it on windows form.




    -- Add Columns To Datagridview

    1. Single Click on Datagridview


    2. Click on small arrow on Top-right of Datagridview


    3. A pop-up Menu appears. Click on "Add Column"





    4. Now in Add Column Dialog Box Change HeaderText to "Name" and Click on Add . This Adds column Name to Datagridview


    5. Now in second column give HeaderText to "Salary"


    6. Now in Third column give HeaderText to "Bonus"


    7. Now in Fourth column give HeaderText to "Total Salary"


    8. Now Add Four Labels to Form and change its text property to :-


    ( I ) Name

    ( II ) Salary
    ( III )Bonus
    ( IV )Total Salary

    9. Take four Masked Textbox from Toolbox and drag them to Windows form






    10. Take a Button and Change its Text Property to "Get Data".





    How To Operate


    1 click on Get Data Button


    2. It will load Default data in datagridview


    3. If you change data in any Datagridview column Then the corresponding value in MaskedTextbox also change




    Code For Datagridview 


    Cellvaluechanged Event vb.net App



    Public Class Form5 Public isdirty As Boolean Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click DataGridView1.Rows(0).Cells(0).Value = "Jorge" DataGridView1.Rows(0).Cells(1).Value = 12000 DataGridView1.Rows(0).Cells(2).Value = 2900 DataGridView1.Rows(0).Cells(3).Value = DataGridView1.Rows(0).Cells(1).Value + DataGridView1.Rows(0).Cells(2).Value End Sub Private Sub MaskedTextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MaskedTextBox1.TextChanged DataGridView1.Rows(0).Cells(0).Value = MaskedTextBox1.Text End Sub Private Sub MaskedTextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MaskedTextBox2.TextChanged DataGridView1.Rows(0).Cells(1).Value = MaskedTextBox2.Text DataGridView1.Rows(0).Cells(3).Value = Val(DataGridView1.Rows(0).Cells(1).Value) + Val(DataGridView1.Rows(0).Cells(2).Value) End Sub Private Sub MaskedTextBox3_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MaskedTextBox3.TextChanged DataGridView1.Rows(0).Cells(2).Value = MaskedTextBox3.Text DataGridView1.Rows(0).Cells(3).Value = Val(DataGridView1.Rows(0).Cells(1).Value) + Val(DataGridView1.Rows(0).Cells(2).Value) End Sub Private Sub MaskedTextBox4_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MaskedTextBox4.TextChanged DataGridView1.Rows(0).Cells(3).Value = MaskedTextBox4.Text DataGridView1.Rows(0).Cells(3).Value = Val(DataGridView1.Rows(0).Cells(1).Value) + Val(DataGridView1.Rows(0).Cells(2).Value) End Sub Private Sub EndEdit(ByVal sender As System.Object, ByVal e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged If DataGridView1.IsCurrentCellDirty Then DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit) End If End Sub Private Sub DataGridView1_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged If e.RowIndex = -1 Then isdirty = True End If If e.ColumnIndex = 0 Then MaskedTextBox1.Text = DataGridView1.Rows(0).Cells(0).Value End If If e.ColumnIndex = 1 Then MaskedTextBox2.Text = DataGridView1.Rows(0).Cells(1).Value DataGridView1.Rows(0).Cells(3).Value = Val(DataGridView1.Rows(0).Cells(1).Value) + Val(DataGridView1.Rows(0).Cells(2).Value) End If If e.ColumnIndex = 2 Then MaskedTextBox3.Text = DataGridView1.Rows(0).Cells(2).Value DataGridView1.Rows(0).Cells(3).Value = Val(DataGridView1.Rows(0).Cells(1).Value) + Val(DataGridView1.Rows(0).Cells(2).Value) End If If e.ColumnIndex = 3 Then MaskedTextBox4.Text = DataGridView1.Rows(0).Cells(3).Value Dim c As Integer = DataGridView1.Rows(0).Cells(3).Value Dim str As String = CInt(c) If Len(str) = 1 Then MaskedTextBox4.Mask = "0" ElseIf Len(str) = 2 Then MaskedTextBox4.Mask = "00" ElseIf Len(str) = 3 Then MaskedTextBox4.Mask = "0,00" ElseIf Len(str) = 4 Then MaskedTextBox4.Mask = "0,000" ElseIf Len(str) = 5 Then MaskedTextBox4.Mask = "00,000" ElseIf Len(str) = 6 Then MaskedTextBox4.Mask = "0,00,000" ElseIf Len(str) = 7 Then MaskedTextBox4.Mask = "00,00,000" End If End If End Sub Private Sub Form5_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load MaskedTextBox4.Mask = "0000000" '' End Sub End Class




    OUTPUT :-




    After Changing value of Cell of Datagridview :-