Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
38 views16 pages

With Gridview

The document discusses how to connect to a SQL database and execute queries using ADO.NET in C#. It demonstrates how to connect to a database, execute queries to retrieve data using SqlCommand and SqlDataReader, populate a DataSet using SqlDataAdapter, and execute stored procedures with and without parameters. It also shows how to add parameters to queries and work with disconnected data in a DataSet.

Uploaded by

abc777uu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views16 pages

With Gridview

The document discusses how to connect to a SQL database and execute queries using ADO.NET in C#. It demonstrates how to connect to a database, execute queries to retrieve data using SqlCommand and SqlDataReader, populate a DataSet using SqlDataAdapter, and execute stored procedures with and without parameters. It also shows how to add parameters to queries and work with disconnected data in a DataSet.

Uploaded by

abc777uu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

http://www.csharp-station.

com/Tutorial/AdoDotNet

sqlconnection conn =new SqlConnection(

"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

// SqlConnection conn = new SqlConnection(

// "Data Source=DatabaseServer;Initial Catalog=Northwind;User


ID=YourUserID;Password=YourPassword");

sqlcommand cmd =new SqlCommand("select CategoryName from Categories", conn);

/* string insertString = @"

insert into Categories

(CategoryName, Description)

values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')"; */

// SqlCommand cmd = new SqlCommand(insertString, conn);

SqlDataReader rdr=cmd. ExecuteNonQuery();

//SqlDataReader rdr=cmd.ExecuteScalar();

while (rdr.Read())

// get the results of each column

string contact = (string)rdr["ContactName"];

string company = (string)rdr["CompanyName"];

string city = (string)rdr["City"];

// print out the results

Console.Write("{0,-25}", contact);

Console.Write("{0,-20}", city);

Console.Write("{0,-25}", company);

Console.WriteLine();

}
finally

// 3. close the reader

if (rdr != null)

rdr.Close();

// close the connection

if (conn != null)

conn.Close();

Working with Disconnected Data - The DataSet and SqlDataAdapter

DataSet dsCustomers = new DataSet();

SqlDataAdapter daCustomers = new SqlDataAdapter(

"select CustomerID, CompanyName from Customers", conn);

daCustomers.Fill(dsCustomers, "Customers");

Using the DataSet

GridView1.DataSource = dsCustomers;

GridView1.DataMember = "Customers";

GridView1.DataBind();

Adding Parameters to Queries

using System;
using System.Data;

using System.Data.SqlClient;

class ParamDemo

static void Main()

// conn and reader declared outside try

// block for visibility in finally block

SqlConnection conn = null;

SqlDataReader reader = null;

string inputCity = "London";

try

// instantiate and open connection

conn = new

SqlConnection("Server=(local);DataBase=Northwind;Integrated
Security=SSPI");

conn.Open();

// don't ever do this

// SqlCommand cmd = new SqlCommand(

// "select * from Customers where city = '" + inputCity + "'";

// 1. declare command object with parameter

SqlCommand cmd = new SqlCommand(

"select * from Customers where city = @City", conn);

// 2. define parameters used in command object

SqlParameter param = new SqlParameter();

param.ParameterName = "@City";

param.Value = inputCity;
// 3. add new parameter to command object

cmd.Parameters.Add(param);

// get data stream

reader = cmd.ExecuteReader();

// write each record

while(reader.Read())

Console.WriteLine("{0}, {1}",

reader["CompanyName"],

reader["ContactName"]);

finally

// close reader

if (reader != null)

reader.Close();

// close connection

if (conn != null)

conn.Close();

Executing Stored Procedures


using System;

using System.Data;

using System.Data.SqlClient;

class StoredProcDemo

static void Main()

StoredProcDemo spd = new StoredProcDemo();

// run a simple stored procedure

spd.RunStoredProc();

// run a stored procedure that takes a parameter

spd.RunStoredProcParams();

// run a simple stored procedure

public void RunStoredProc()

SqlConnection conn = null;

SqlDataReader rdr = null;

Console.WriteLine("\nTop 10 Most Expensive Products:\n");

try

// create and open a connection object

conn = new

SqlConnection("Server=(local);DataBase=Northwind;Integrated
Security=SSPI");

conn.Open();
// 1. create a command object identifying

// the stored procedure

SqlCommand cmd = new SqlCommand(

"Ten Most Expensive Products", conn);

// 2. set the command object so it knows

// to execute a stored procedure

cmd.CommandType = CommandType.StoredProcedure;

// execute the command

rdr = cmd.ExecuteReader();

// iterate through results, printing each to console

while (rdr.Read())

Console.WriteLine(

"Product: {0,-25} Price: ${1,6:####.00}",

rdr["TenMostExpensiveProducts"],

rdr["UnitPrice"]);

finally

if (conn != null)

conn.Close();

if (rdr != null)

rdr.Close();

}
}

// run a stored procedure that takes a parameter

public void RunStoredProcParams()

SqlConnection conn = null;

SqlDataReader rdr = null;

// typically obtained from user

// input, but we take a short cut

string custId = "FURIB";

Console.WriteLine("\nCustomer Order History:\n");

try

// create and open a connection object

conn = new

SqlConnection("Server=(local);DataBase=Northwind;Integrated
Security=SSPI");

conn.Open();

// 1. create a command object identifying

// the stored procedure

SqlCommand cmd = new SqlCommand(

"CustOrderHist", conn);

// 2. set the command object so it knows

// to execute a stored procedure

cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which

// will be passed to the stored procedure


cmd.Parameters.Add(

new SqlParameter("@CustomerID", custId));

// execute the command

rdr = cmd.ExecuteReader();

// iterate through results, printing each to console

while (rdr.Read())

Console.WriteLine(

"Product: {0,-35} Total: {1,2}",

rdr["ProductName"],

rdr["Total"]);

finally

if (conn != null)

conn.Close();

if (rdr != null)

rdr.Close();

}
Own Practise:

Default.aspx.cx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page


{
//http://technico.qnownow.com/how-to-insert-update-delete-rows-in-asp-net-gridview-
control/
SqlConnection conn = new SqlConnection("Data Source=93.91.24.115;Initial
Catalog=RLATemp;User ID=IMSDBManager;Password=kk");

protected void Page_Load(object sender, EventArgs e)


{
conn.Open();
DataSet dsCustomers = new DataSet();
//DataSet ds2 = new DataSet();

SqlDataAdapter daCustomers = new SqlDataAdapter(


"select * from APolicies", conn);

daCustomers.Fill(dsCustomers, "Policies");

GridView1.DataSource = dsCustomers;
GridView1.DataMember = "Policies";
GridView1.DataBind();

string insertString = "Select PolicyRefNo from APolicyRefNo";


SqlCommand cmd = new SqlCommand(insertString, conn);
SqlDataReader dataReader=cmd.ExecuteReader();
while (dataReader.Read())
{
DropDownList1.Items.Add(dataReader["PolicyRefNo"].ToString());
}
dataReader.Close();

insertString = "Select CustomerID from ACustomer";


SqlCommand cmd1 = new SqlCommand(insertString, conn);
SqlDataReader dataReader1 = cmd1.ExecuteReader();
while (dataReader1.Read())
{
DropDownList2.Items.Add(dataReader1["CustomerID"].ToString());
}

dataReader1.Close();

insertString = "Select PolicyRefNo from APolicyRefNo";


SqlCommand cmd2 = new SqlCommand(insertString, conn);
SqlDataReader dataReader2 = cmd2.ExecuteReader();
while (dataReader2.Read())
{
DropDownList3.Items.Add(dataReader2["PolicyRefNo"].ToString());
}
dataReader2.Close();

}
protected void Button2_Click(object sender, EventArgs e)
{
string insertString = @"insert into APolicyRefNo values (@values);";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("@values", tbxPolicies.Text);
cmd.ExecuteNonQuery();

}
protected void Button1_Click(object sender, EventArgs e)
{
string insertString = @"insert into ACustomer values (@values1,@values2,@values3);";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("@values1", tbXCustomerName.Text);
cmd.Parameters.AddWithValue("@values2", tbxCustomerCity.Text);
cmd.Parameters.AddWithValue("@values3", tbxCustomerCountry.Text);
cmd.ExecuteNonQuery();

}
protected void Button4_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr = null;

dt.Columns.Add(new DataColumn("PolicyRefNo", typeof(string)));


dt.Columns.Add(new DataColumn("CustomerID", typeof(string)));

for (int i=0; i< GridView1.Rows.Count;i++)


{
dr = dt.NewRow();
dr["PolicyRefNo"] = GridView1.Rows[i].Cells[1].Text.ToString();
dr["CustomerID"] = GridView1.Rows[i].Cells[2].Text.ToString();
dt.Rows.Add(dr);
}

//dt.Columns.Add(new DataColumn("Column2", typeof(string)));


//dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["PolicyRefNo"] = DropDownList3.SelectedValue;
dr["CustomerID"] = DropDownList2.SelectedValue;
dt.Rows.Add(dr);

//dr = dt.NewRow();

////Store the DataTable in ViewState


//ViewState["CurrentTable"] = dt;

GridView1.DataSource = dt;
GridView1.DataBind();

}
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{

}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ProductID = e.RowIndex;
string SPolicyRefNo = ""; string SCustomerID = "";
SPolicyRefNo = GridView1.Rows[ProductID].Cells[1].Text.ToString();
SCustomerID = GridView1.Rows[ProductID].Cells[2].Text.ToString();
DeleteProduct(SPolicyRefNo, SCustomerID);
GridView1.EditIndex = -1;
GridView1.DataBind();
}

private void DeleteProduct(string SPolicyRefNo, string SCustomerID)


{
string sql = String.Format(@"Delete from APolicies where PolicyRefNo = '{0}' AND
CustomerID='{1}'", SPolicyRefNo,SCustomerID);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}

protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)


{

}
}

Default2.aspx.cx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class Default2 : System.Web.UI.Page


{
SqlConnection conn = new SqlConnection("Data Source=93.91.24.115;Initial
Catalog=RLATemp;User ID=IMSDBManager;Password=kk");
protected void Page_Load(object sender, EventArgs e)
{

//SqlCommand cmd = new SqlCommand("select * from RateChange11Jul2012", conn);


DataSet dsCustomers = new DataSet();

SqlDataAdapter daCustomers = new SqlDataAdapter(


"select * from Sales", conn);

daCustomers.Fill(dsCustomers, "Sales");

GridView1.DataSource = dsCustomers;
GridView1.DataMember = "Sales";
GridView1.DataBind();

DropDownList1.Items.Add("003");
DropDownList2.Items.Add("300");
}
protected void Button1_Click(object sender, EventArgs e)
{
//int i = Convert.ToInt16(DropDownList2.SelectedValue);

int returnValue = 0;
string temp;
int i;
string insertString = @"insert into Sales values (@values, @dd); Select @@Identity;";
SqlCommand cmd = new SqlCommand(insertString, conn);
//cmd.CommandType.
cmd.Parameters.AddWithValue("@values", DropDownList2.SelectedValue);
cmd.Parameters.AddWithValue("@dd",System.DateTime.Now);
conn.Open();
//returnValue = cmd.ExecuteNonQuery();
//string query2 = "Select @@Identity";
//cmd.CommandText = query2;
temp = Convert.ToString(cmd.ExecuteScalar());
}
}

customerInfo.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CustomerInfo.aspx.cs"


Inherits="CustomerDetails_CustomerInfo" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>


<%@ Register Src="~/UserControls/SearchCustomer.ascx" TagName="SearchCustomer" TagPrefix="uc1" %>
<!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>Quick Customer Info</title>
<script language="javascript" type="text/javascript">
function IsValid(val) {
var keyCode = val.keyCode;
if (keyCode >= 48 && keyCode <= 57)
return true;
else if (keyCode == 32 || keyCode == 43 || keyCode == 40 || keyCode == 41) //keycode for space + ( )
return true;
else
return false;
return true;
}
</script>
<link href="~/StyleSheets/rla.css" rel="stylesheet" type="text/css" />
<%-- <link href="../StyleSheets/design.css" rel="stylesheet" type="text/css" />--%>
<link href="~/inc/Quotedesign.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<table style="width: 100%">
<tr>
<td>
<asp:Panel ID="pnlPolicyFor" runat="server" Width="100%">
<table style="width: 100%">
<tr>
<td bgcolor="#5D7B9D" colspan="2" height="20px">
<asp:Label ID="lblPolicyFor0" runat="server" ForeColor="White"
Text="Customer Details"></asp:Label>
</td>
</tr>
<tr>
<td style="width: 10%">
<asp:Label ID="lblPolicyFor" runat="server" Text="Customer
Type :"></asp:Label>
</td>
<td style="width: 90%">
<asp:RadioButtonList ID="rbtnlCustomer" runat="server"
AutoPostBack="True" OnSelectedIndexChanged="rbtnlCustomer_SelectedIndexChanged"
RepeatDirection="Horizontal">
<asp:ListItem Selected="True" Text="Single Person" Value="Person" />
<asp:ListItem Text="Company" Value="Company" />
</asp:RadioButtonList>
</td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblCustomerRefNo" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Panel ID="pnlCustomerPerson" runat="server">
<table style="width: 100%">
<tr>
<td style="width: 70%">
<table style="width: 100%; vertical-align: top; text-align: left;">
<tr>
<td align="right" style="width: 10%">
<asp:Label ID="Label9" runat="server"
Text="Title :"></asp:Label>
</td>
<td align="left" valign="middle" style="width: 90%">
<asp:TextBox ID="tbxTitle" runat="server" Width="50px"
TabIndex="1"></asp:TextBox>
<asp:Panel ID="pnlTitle" runat="server">
<div style="border: 1px outset white; width: auto;
background-color: #FFFFFF;">
<asp:UpdatePanel runat="server" ID="up2">
<ContentTemplate>
<asp:RadioButtonList ID="rbtnlTitle"
runat="server" AutoPostBack="true" OnSelectedIndexChanged="rbtnlTitle_SelectedIndexChanged">
<asp:ListItem Text="Mr" />
<asp:ListItem Text="Mrs" />
<asp:ListItem Text="Miss" />
<asp:ListItem Text="Ms" />
<asp:ListItem Text="Other" Value="" />
</asp:RadioButtonList>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</asp:Panel>
<cc1:PopupControlExtender ID="pceTitle" runat="server"
TargetControlID="tbxTitle"
PopupControlID="pnlTitle" CommitProperty="value"
Position="Bottom" CommitScript="e.value += '';" />
</td>
</tr>
<tr>
<td align="right" valign="middle">
<asp:Label ID="lblFirstName" runat="server" Text="First Name
:"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxFirstName" runat="server" Width="300px"
TabIndex="2"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" valign="middle">
<asp:Label ID="Label22" runat="server" Font-Names="Century"
ForeColor="Red" Text="*"></asp:Label>
<asp:Label ID="lblLastName" runat="server" Text="Last
Name :"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxLastName" runat="server" Width="300px"
TabIndex="3"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" valign="middle">
<asp:Label ID="Label4" runat="server"
Text="Company :"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxCompany" runat="server"
Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" valign="middle">
<asp:Label ID="Label23" runat="server" Font-Names="Century"
ForeColor="Red" Text="*"></asp:Label>
<asp:Label ID="lblHomeTele" runat="server" Text="Tel No
(R) :"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxHomeTele" runat="server"
Width="150px"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" valign="middle">
<asp:Label ID="lblMobile" runat="server" Text="Mobile
No :"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxMobile" runat="server"
Width="150px"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" valign="top">
<asp:Label ID="lblEmail" runat="server" Text="E-
mail :"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxEmail" runat="server"
Width="260px"></asp:TextBox>
<asp:RegularExpressionValidator ID="EmailValidate"
runat="server" ControlToValidate="tbxEmail"
ErrorMessage="Error !" ForeColor="White"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
BackColor="Red" Font-
Size="11px"></asp:RegularExpressionValidator>
</td>
</tr>
</table>
</td>
<td valign="bottom" align="left" style="width: 30%">
<asp:ImageButton ID="btnProceed" runat="server"
ImageUrl="~/images/proceed.jpg" TabIndex="8"
OnClick="btnProceed_Click" />
</td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
<tr>
<td>
<asp:Panel ID="pnlCustomerCompany" runat="server">
<table style="width: 100%">
<tr>
<td style="width: 70%">
<table style="width: 100%; vertical-align: top; text-align: left;">
<tr>
<td align="right" valign="middle" style="width: 10%">
<asp:Label ID="Label3" runat="server" Font-Names="Century"
ForeColor="Red" Text="*"></asp:Label>
<asp:Label ID="lblCompany" runat="server"
Text="Company :"></asp:Label>
</td>
<td align="left" valign="middle" style="width: 90%">
<asp:TextBox ID="tbxCompanyName" runat="server"
Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right" valign="middle">
<asp:Label ID="Label12" runat="server" Font-Names="Century"
ForeColor="Red" Text="*"
Visible="False"></asp:Label>
<asp:Label ID="lblDirecter" runat="server"
Text="Directer :"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxDirecter" runat="server"
Width="300px"></asp:TextBox>
</td>
</tr>
<tr>
<td align="right">
<asp:Label ID="Label8" runat="server" Font-Names="Century"
ForeColor="Red" Text="*"></asp:Label>
<asp:Label ID="lblCompanyTele" runat="server" Text="Tel No
(O) :"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxCompanyTele" runat="server"
Width="150px" TabIndex="12"></asp:TextBox>&nbsp;&nbsp;
<asp:TextBox ID="tbxExtension" runat="server" Width="35px"
TabIndex="13"></asp:TextBox><asp:Label
ID="lblCompanyExtensiion" runat="server"
Text="(Ext)"></asp:Label>
</td>
</tr>
<tr>
<td align="right" valign="top">
<asp:Label ID="Label5" runat="server" Text="E-
mail :"></asp:Label>
</td>
<td align="left" valign="middle">
<asp:TextBox ID="tbxCompanyEmail" runat="server"
Width="260px"></asp:TextBox>
<asp:RegularExpressionValidator
ID="RegularExpressionValidator1" runat="server" ControlToValidate="tbxCompanyEmail"
ErrorMessage="Error !" ForeColor="White"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
BackColor="Red" Font-
Size="11px"></asp:RegularExpressionValidator>
</td>
</tr>
</table>
</td>
<td valign="bottom" align="left" style="width: 30%">
<asp:ImageButton ID="btnProceedfurther" runat="server"
ImageUrl="~/images/proceed.jpg"
TabIndex="8" OnClick="btnProceedfurther_Click" />
</td>
</tr>
</table>
</asp:Panel>
</td>
</tr>
<tr>
<td align="left">
<asp:Label ID="lblSaveMessage" runat="server" Font-Size="11px"
ForeColor="Red"></asp:Label>
</td>
</tr>
</table>
<asp:Panel ID="Panel1" runat="server" Height="250px" Width="100%">
<uc1:SearchCustomer ID="SearchCustomer1" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

You might also like