Thursday 27 June 2013

Complex Data Binding in Windows Forms

Complex Data Binding in Windows Forms

We will build Windows Form that will display all student in a bound ListBox and thestudents's associated marks in a bound DataGrid. A more complex DataSet will be needed that provides the relationship path to traverse from student to marks  using the primary key of student (stdid) to foreign key in marks (stdid). we will have to do data bindings for both the ListBox control and the DataGrid control.

Create a New Project in VS .NET

  1. Create a new project in VS .NET by choosing File, New, and then choosing the Project option..
  2. When the New Project dialog box appears, choose  Visual C# Projects and Windows Applications. Name this project "comlexdatabinding". This creates a default form for you to start from.
Add the Data Connection and Two Data Adapters
we will need to access both the student  table and themarks table, so two data adapters will be created, each populating different controls but using one database connection.
From the Data tab of the Toolbox, drag aOledbDataAdapter object into your form. This will automatically invoke the Data Adapter Configuration Wizard. Both the data connection and the data adapter can be fully configured here.
  1. The wizard starts with the Choose our Data Connection dialog box. If   there  already exist a connection defined in your project,then it will be placed in the dialog box; otherwise, choose to create a new connection and specify the appropriate connection information .
  2. Choose the Use SQL Statements option.
  3. we  will be presented with a Generate the SQL Statements dialog box where you will simply type in a valid SQL statement, or you can use the Query Builder option to formulate the SQL query.such as:
    SELECT stdid,stdname FROM student
  4. Finally, the wizard will show you the tasks that it has done and indicate whether the oledbDataAdapter has been configured successfully.

  1.  we need one more data adapter for access to the mrks  table. Drag another oledbDataAdapter object onto the form.
    1. Again, the wizard starts with the Choose Your Data Connection dialog box.
    2. Choose the Use SQL Statements option.
    3. we  will be presented with a Generate the SQL Statements dialog box where you will type the following query:
      SELECT subid, stdid, subname,mark
      FROM marks
      d .Then the wizard will show we  the tasks that it has done and indicate whether the oledbDataAdapter has been configured successfully .
      
      
      Generate a DataSet
      Now that the OledbDataAdapter and DataConnection objects have been configured and added to the form, you must generate a DataSet and then add an instance of this DataSetto the form.
      1. From the Data menu in Visual Studio, simply choose the Generate Dataset option.
      2.                   
        XML Schema editor—STUDENTDS.xsd schema file.
        Next, drag a Relation object onto the Orders table
         Adding the ListBox and DataGrid Controls
         create the ListBox to display all of the Sudent Names from the Student table.
        1. Drag a ListBox object from the Windows Forms tab of the Toolbox onto the Form.
        2. Press F4 to go right to the properties of this ListBox.
        3. For the DataSource property, you will need to select the dtatsaet1 data source.
        4. For the DisplayMember property, you will select student , expand this node, and select studentname.shows the complete ListBox property.
         the DataGrid control to display all of the Orders that are associated with a particular Company that is selected.
        1. Drag a DataGrid object from the Windows Forms tab of the toolbox onto the Form.
        2. Press F4 to go right to the properties of this DataGrid.
        3. For the DataSource property, you will need to select the student data source.
        4. And, for the DisplayMember property, you will select and expand student, and then select marks
        Just double-click on the form to create a handler for the form's Load event. You will need to clear theDataSet first, and then fill each data adapter that we defined.
        datsaet1.Clear()
        OledbDataAdapter1.Fill(dataset1)
        OledbDataAdapter2.Fill(dataset1)
         

Using SqlCommandBuilder show SQL statement

Using SqlCommandBuilder show SQL statement


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection newConnection = new 
    SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS;
    initial catalog=newDatabase;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        newConnection.Open();
        SqlDataAdapter ad = new SqlDataAdapter("select * from emp_tbl", newConnection);
        SqlCommandBuilder cmd = new SqlCommandBuilder(ad);
        Label1.Text = "SQL Select Command is: " + ad.SelectCommand.CommandText;
        SqlCommand updateCommand = cmd.GetUpdateCommand();
        Label2.Text="SQL Update Command is: " +updateCommand.CommandText;
        SqlCommand insertCommand = cmd.GetInsertCommand();
        Label3.Text="SQL Insert Command is: " +insertCommand.CommandText;
        SqlCommand deleteCommand = cmd.GetDeleteCommand();
        Label4.Text="SQL Delete Command is: " +deleteCommand.CommandText;
    }    
}
Out Put:

Insert Data using SqlCommandBuilder in ADO.NET using C#

Insert Data using SqlCommandBuilder in ADO.NET using C#


SqlCommandBuilder: This enables you to UPDATE database tables without having to write the commands, reducing the likelihood of errors. This class cannot be inherited.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection newConnection = new 
    SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS;
    initial catalog=newDatabase;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        newConnection.Open();
        SqlDataAdapter ad = new SqlDataAdapter("select * from emp_tbl", newConnection);
        SqlCommandBuilder cmd = new SqlCommandBuilder(ad);
        DataSet ds = new DataSet();
        ad.Fill(ds);
        DataRow MyRow = ds.Tables[0].NewRow();
        MyRow["emp_id"] = 1234;
        MyRow["emp_name"] = "Anjali";
        MyRow["emp_age"] = "25";
        ds.Tables[0].Rows.Add(MyRow);
        ad.Update(ds);
    }    
}
Out Put:

Inserts (Create) a new table in ASP .Net using C#

Inserts (Create) a new table in ASP .Net using C#



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection newConnection = new 
    SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS;
    initial catalog=newDatabase;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
     newConnection.Open();
     SqlCommand cmd = new 
     SqlCommand("create table Emp_Login (UserName nvarchar(20), Password nvarchar(20))"+
     "insert into Emp_Login (UserName,Password) values ('atul','1234');", newConnection);
     cmd.ExecuteNonQuery();
     newConnection.Close();
    }
    
    
}

Out Put:

How to update a table data in GridView Control Using C#

How to update a table data in GridView Control Using C#



using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection newConnection = new 
    SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS;
    initial catalog=newDatabase;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        bindData();
    }
    public void bindData()
    {
        SqlCommand cmd = new SqlCommand("select * from emp_tbl", newConnection);
        newConnection.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            GridView1.DataSource = dr;
            GridView1.DataBind();
        }
        newConnection.Close();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        bindData();

        
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        newConnection.Open();
        SqlCommand cmdd = new 
        SqlCommand("update emp_tbl set nme=@a,age=@b
        where emp_id='"+TextBox3.Text+"'", newConnection);
        cmdd.Parameters.Add("@a",TextBox1.Text);
        cmdd.Parameters.Add("@b", TextBox2.Text);
        cmdd.ExecuteNonQuery();
        newConnection.Close();
        bindData();
    }
    
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string s = GridView1.DataKeys[e.RowIndex].Value.ToString();

        newConnection.Open();
        SqlCommand cmdd = new 
        SqlCommand("select * from emp_tbl where emp_id='" + s + "'", newConnection);
        SqlDataReader dr1 = cmdd.ExecuteReader();
        if (dr1.Read())
        {
            TextBox1.Text = dr1["nme"].ToString();
            TextBox2.Text = dr1["age"].ToString();
            TextBox3.Text = dr1["emp_id"].ToString();
        }
        newConnection.Close();
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bindData();
    }
}

Out Put: Click on the Edit Button which row you want to update.
Click on the Update Button.
Edit your Values and click on Update, value is Updated.

How to Get Table Information in ASP .NET

How to Get Table Information in ASP .NET


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection newConnection = new 
    SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS;
    initial catalog=newDatabase;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("SELECT TABLE_TYPE, 
        TABLE_NAME FROM INFORMATION_SCHEMA.TABLES", newConnection);
        newConnection.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            Label1.Text ="Table Type: "+dr[0].ToString();
            Label2.Text = "Table Name: "+dr[1].ToString();
        }
        newConnection.Close();
    }
}
Out Put:

How to execute multiple SQL statements using a SqlCommand object

How to execute multiple SQL statements using a SqlCommand object


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection newConnection = new 
    SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS;
    initial catalog=newDatabase;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
      SqlCommand cmd = new 
      SqlCommand("insert into emp_tbl (nme,age,emp_id) values ('atul', '24','1234');" +
      "select nme,age from emp_tbl where emp_id=1234 "+
      "update emp_tbl set nme='Anjali' where emp_id=1234" +
      "select nme,age from emp_tbl where emp_id=1234 ;",newConnection);
      newConnection.Open();
      SqlDataReader dr = cmd.ExecuteReader();
      if (dr.Read())
      {
          GridView1.DataSource = dr;
          GridView1.DataBind();
      }
      newConnection.Close();
    }
}
Out Put:

Executing a Parameterized Query with SqlCommand in ASP. NET

Executing a Parameterized Query with SqlCommand in ASP. NET


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection newConnection = new 
    SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; 
    initial catalog=newDatabase;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlCommand sqlCommand = new 
        SqlCommand("select * from emp_tbl where emp_id > @id",newConnection);
        sqlCommand.Parameters.Add("@id", SqlDbType.Int).Value=123;
        SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCommand);
        DataTable sqlDt = new DataTable();
        sqlDa.Fill(sqlDt);
        foreach (DataRow row in sqlDt.Rows)
        {
            Response.Write(row["nme"]);
            Response.Write(row["emp_id"]);
            Response.Write(row["age"]);
        }
    }
}
Out Put:

How To Build a connection string from component parameters and display It.

How To Build a connection string from component parameters and display It.


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{    
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnectionStringBuilder sub = new SqlConnectionStringBuilder();
        sub.DataSource =@"\SQLEXPRESS";
        sub.InitialCatalog = "newDatabase";
        sub.IntegratedSecurity = true;
        sub.MinPoolSize = 5;
        sub.MinPoolSize = 15;
        sub.LoadBalanceTimeout = 600;
        sub.ConnectionReset = true;
        Response.Write("" + sub.ConnectionString);   
    }   
}
Out Put:

Build SqlConnection StringBuilder from connection string

Build SqlConnectionStringBuilder from connection string

Provides a simple way to create and manage the contents of connection strings used by the SqlConnection class.
Property:
  1. ApplicationName
  2. AsynchronousProcessing
  3. AttachDBFilename
  4. BrowsableConnectionString
  5. ConnectionReset
  6. ConnectionString
  7. ConnectTimeout
  8. ContextConnection
  9. CurrentLanguage
  10. DataSource
  11. FailoverPartner
  12. InitialCatalog
  13. IntegratedSecurity
  14. IsFixedSize
  15. IsReadOnly
  16. LoadBalanceTimeout
  17. MaxPoolSize
  18. MinPoolSize
  19. MultipleActiveResultSets
  20. NetworkLibrary
  21. PacketSize
  22. PersistSecurityInfo
  23. TransactionBinding
  24. System.Transactions
  25. TrustServerCertificate
  26. TypeSystemVersion
  27. UserID
  28. UserInstance
  29. WorkstationID
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    string conString=@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; 
    initial catalog=newDatabase;integrated security=true;
    Min Pool Size=5;Max Pool Size=15;Connection Reset=True; Connection Lifetime=600;";
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnectionStringBuilder sub = new SqlConnectionStringBuilder(conString);
        Response.Write("Parsed SQL Connection String Parameters:");
        Response.Write("  Database Source = " + sub.DataSource);
        Response.Write("  Database = " + sub.InitialCatalog);
        Response.Write("  Use Integrated Security = " + sub.IntegratedSecurity);
        Response.Write("  Min Pool Size = " + sub.MinPoolSize);
        Response.Write("  Max Pool Size = " + sub.MaxPoolSize);
        Response.Write("  Lifetime = " + sub.LoadBalanceTimeout);
        Response.Write("  Connection Reset = " + sub.ConnectionReset);
    }  
}

Retrieving Data Using a SQL Server Stored Procedure IN ASP.NET

Retrieving Data Using a SQL Server Stored Procedure IN ASP.NET

Step 1. The Design Code is:
<%@ Page Language="C#" AutoEventWireup="true"  
Codevirtual="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AjaxControlToolkit" 
namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body><form id="form1" runat="server">
<div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
  BorderStyle="Solid" BorderWidth="2px" 
        Height="86px"
        Width="258px" >  
 <RowStyle BackColor="White" BorderColor="#333333" BorderStyle="Solid" 
 BorderWidth="2px" />
  <Columns><asp:BoundField DataField="nme" HeaderText="Name" />
 <asp:BoundField DataField="age" HeaderText="Age" />
 <asp:BoundField DataField="emp_id" HeaderText="Employe ID" />
  </Columns>
    <SelectedRowStyle BorderStyle="Solid" />
    <HeaderStyle BackColor="#CCCCCC" BorderStyle="Inset" BorderWidth="2px" />
    <EditRowStyle BorderStyle="Solid" BorderWidth="2px" />
 </asp:GridView>   </div>
   <br /><br /> 
    </form>
</body>
</html>
Stored Procedure:
CREATE PROCEDURE  SelectEmpDetails @id nchar(10)
AS
BEGIN
SELECT 
* FROM  emp_tbl  WHERE  emp_ID=@id
END
Step 2. Default.aspx.cs Code
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection newConnection = new 
    SqlConnection(@"Data Source=R4R-3EFD13BB468\SQLEXPRESS; 
    initial catalog=newDatabase;integrated security=true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        newConnection.Open();
        SqlCommand cmdd = new SqlCommand("SelectEmpDetails", newConnection);
        cmdd.CommandType = CommandType.StoredProcedure;
        cmdd.Parameters.Add("@id", SqlDbType.Int).Value = 1234;
        SqlDataReader dr = cmdd.ExecuteReader();
        if (dr.HasRows)
        {
            GridView1.DataSource = dr;
            GridView1.DataBind();
        }
        newConnection.Close();
    }
    
}
Out Put:

How to Get all Information SQL Server in ASP .NET

How to Get all Information SQL Server in ASP .NET

Step 1. Drag a text Box and a Button control on your page. Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  
Codevirtual="Default.aspx.cs" Inherits="_Default" %>
<%@ Register assembly="AjaxControlToolkit" 
namespace="AjaxControlToolkit" tagprefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table><tr>
    <td>Enter the ID:</td><td>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td><td>
    <asp:Label ID="Label1" runat="server"></asp:Label>
    </td></tr>
    <tr><td>
    <asp:Button ID="Button1" runat="server" Text="Submit" 
	onclick="Button1_Click" /></td></tr>
    </table>
    </div>
   
    </form>
</body>
</html>
Step 2. Default.aspx.cs Code

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page 
{
  SqlConnection newConnection = new SqlConnection(@"Data 
  Source=R4R-3EFD13BB468\SQLEXPRESS;
  initial catalog=newDatabase;integrated security=true;");
  protected void Page_Load(object sender, EventArgs e)
  { 
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
  newConnection.Open();
  SqlCommand cmd = new SqlCommand("select age,nme from emp_tbl where emp_id=@id",
  newConnection);
  cmd.Parameters.AddWithValue("@id", TextBox1.Text);
  SqlDataReader dr = cmd.ExecuteReader();
  if (dr.Read())
  {
  Label1.Text = "Employee Name: " + dr["nme"].ToString() + 
  " and Your age is " + dr["age"].ToString();
  }
  else
  {
  Label1.Text = "Enter Correct Emp ID";
  }
  }
}

Step 3. Run the Application.