Notes of
Notes of
ADO.NET
ADO.NET is a new evolution of ADO ( ActiveX Data Object ) technology. ADO.NET
technology is a disconnected model. It means, it connects to the database when
required, fetches the information and then gets disconnected. ADO.NET is a model
used by .NET application to communicate with a database for retrieving, accessing and
updating the data. With the help of ADO.NET we can retrieved from one data source
and saved its into another database.
There are maximum five steps for creating a connection and accessing the database
is:
(i) Creating a connection object
(ii) Creating a command object
(iii) Opening a connection
(iv) Execute an sql statement in the command object
(v) Close the connection
(e) “Provider ” : It is used to set the name of the provider for the
connection. This parameter is used only in the
“ConnectionString ” property of the “ OledbConnection ”
class , not for “ SqlConnection ” class.
For Example :
“ OR ”
SqlConnection con = new SqlConnection ( “
Server = Server_name ; Database = Database_name
; Integrated Security = sspi “) ;
“ OR ”
SqlConnection con = new SqlConnection ( “
Server = Server_name ; Database = Database_name
; User Id = user_name ; Password = password “) ;
“ OR ”
SqlConnection con = new SqlConnection ( ) ;
“OR”
OledbConnection con = new OledbConnection ( “
Provider = microsoft.jet.oledb.4.0 ; data source =
c: / ranjit / mydatabase_name.mdb ; User id ; Password
“ ) ;
“OR”
For Example:
SqlCommand cmd1= new SqlCommand(“Insert into
table1(roll,name) values(‘101’,’ranjit’)”,con);
Syntax: Connection_object_name.Open( ) ;
Example : con.open( ) ;
For Example:
int n=cmd.ExecuteNonQuery();// In the case of
insert/update/delete
SqlDataReader dr=cmd.ExecuteReader();// In the case of
select
Syantx : Con_obj_name.Close ( ) ;
Example : con.Close( ) ;
int r = cmd.ExecuteNonQuery();
if (r == 1)
{
Console.WriteLine("Successfully inserted value");
}
else
{
Console.WriteLine("Value not inserted");
}
con.Close();
}
public void display()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Select * from table1", con);
OleDbDataReader dr = cmd.ExecuteReader();
Console.Clear();
Console.WriteLine("================================");
Console.WriteLine("SL. No \t Cust Name \t Contact");
Console.WriteLine("================================");
while (dr.Read())
{
Console.WriteLine(dr[0].ToString() + "\t" + dr[1].ToString()+"\t\t"+dr[2].ToString());
}
Console.WriteLine("\n\n================================");
con.Close();
}
public void count()
{
con.Open();
OleDbCommand cmd = new OleDbCommand("Select Count(*) from table1", con);
String c=cmd.ExecuteScalar().ToString();
Console.WriteLine("Total number of records is : " + c);
con.Close();
}
}
class Program
{
static void Main(string[] args)
{
int i=0;
first f1 = new first();
do
{
Console.WriteLine("1. Insert");
Console.WriteLine("2. Display");
Console.WriteLine("3. Count Record");
Console.WriteLine("4. Exit");
Console.WriteLine("Enter any choice (1/2/3) : ");
i=Int32.Parse(Console.ReadLine());
if (i == 1)
7
{
f1.insert();
}
else if (i == 2)
{
f1.display();
}
else if (i == 3)
{
f1.count();
}
}while(I < 4);
}
}
Example :--
cmd.Parameters.Add(param1);
cmd.Parameters.Add(param2);
cmd.ExecuteNonQuery();
con.Close();
}
1. (ii) <provider>DataReader Class : The “DataReader” class
inherited from the “IDataReader” class. A DataReader is the simplest and
fastest way of selecting some data from a data source.we can not directly
instantiate of DataReader object it means we can not use new keyword for
creating the object of DataReader. The DataReader is forword-only and read-
only stream from of data from the database. The DataReader retrieving data as
only one record is brought into memory at a time. The dr.Read( ) method will
advance to the next record in the stream.
HasRows :Gets a value that indicates whether the DataReader contains one or
more rows.
FieldCount ::Gets the number of columns in the current row.
IsClosed : Indicates whether the DataReader is closed or not.
For Example
public void diaply()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from stud_info", con);
SqlDataReader dr = cmd.ExecuteReader();
“Or”
IDataReader dr=cmd.ExecuteReader();
while (dr.Read())
{
Console.Write(dr.GetString(0) + "\t");
Console.Write(dr.GetValue(1) + "\t");
Console.Write(dr.GetInt32(2) + "\t");
Console.Write( dr.GetDateTime(3).ToShortDateString() + "\n");
}
Console.ReadLine();
Con.Close( );
}
For Example:
SqlDataAdapter da = new SqlDataAdapter( “Select
* from Table1 “ , con ) ;
Creating DataTable
ds.Tables.Add(dt1);
11
ds.Tables.Add(dt2);
Creating DataColumn
DataColumn col1 = new DataColumn( );
DataColumn col2 = new DataColumn( String Column_name );
DataColumn col3= new DataColumn(String Column_name , Type
DataType);
DataColumn col4 = new DataColumn(String Column_name ,
Type
DataType , String expression ) ;
Example :
dt.Columns.Add( );
dt.Columns.Add( dc2 );
dt.Columns.Add(“Name”);
dt.Columns.Add(" Price ", Type.GetType("System.Int32"));
dt.Columns.Add("Total", Type.GetType("System.Int32") ,
“Sum(Price)”);
DataRow
The DataRow object contains the data in the DataTable. Each DataRow
has one item per DataColumn in the Columns. It is similar to the Row
collection of the database.
DataRow dr ; DataRow dr ;
dr = dt.NewRow( ); dr = dt.NewRow( ) ;
dr[0] = “ 101 ”; dr[“Roll”] = “101” ;
dr[1] = “Ranjit”; “ OR ” dr[“Name”] = “Ranjit” ;
dr[2] = “MCA” ; dr[“ Class “] = “MCA” ;
dt.Rows.Add( dr); dt.Rows.Add( dr ) ;
“ OR “
pk[1] = dt.Columns["Class"];
dt.PrimaryKey = pk;
dt.Columns["Roll"].AutoIncrement = true;
dt.Columns["Roll"].AutoIncrementStep = 1;
dt.Columns["Roll"].AutoIncrementSeed = 100;
dt.Columns["Roll"].ReadOnly = true;
Note: The DataColumn class also provides properties for definng a column as a ReadOnly ,
AutoIncrement column , AutoIncrementStep with the numbering starting from i.e. AutoIncrementSeed.
eg:
ds.Relations.Add ( R1) ;
e.g :
eg:
parent_column = ds.Tables[“District”].Columns[“Dist”] ;
child_column = ds.Tables[“Employee”].Columns[“Dist”] ;
ds.Relations.Add(“emp_to_dist” , parent_column , child_column ) ;
DataSet
Student DataTable
Employee DataTable
MessageBox.Show(ds.Tables[0].Rows[2].ItemArray[2].ToString()); M Tech
MessageBox.Show(ds.Tables[1].Rows[2][2].ToString()); Siwan
MessageBox.Show(ds.Tables[1].Rows[0].ItemArray[1].ToString()); Ranjit
MessageBox.Show(ds.Tables[1].Rows[0][2].ToString()); Patna
MessageBox.Show(ds.Tables[1].Rows[3].ItemArray[2].ToString()); Jahanabad
MessageBox.Show(ds.Tables[1].Rows[0][2].ToString()); Patna
DataGridView Control
DataGridView control is the main data display control for displaying and
editing tabular data in windows applications. The DataGridView Control has
many properties, methods, and events for customizing its appearance and
behavior. When we have to display tabular data either with small number of
15
Property
1. AllowUserToAddRows
2. AllowUserToDeleteRows
3. AllowUserToResizeColumns
4. AllowUserToResizeRows
5. AutoGenerateColumns
6. BackgroundColor
7. CurrentCell
8. DataSource
9. DataMember
10. AutoSizeColumnsMode
11. Columns
12. DefaultCellStyle
13. MultiSelect
14. RowHeaderVisible
15. RowDefaultCellStyle
16. RowTemplate
17. ScrollBars
Methods Description
GetCellCount It gets the number of cells that satisfy
the provided filter.
HitTest It returns the location information such
as rows and columns index given x and y
co-ordinates
Events Description
CellClick Occurs when any part of a cell is clicked
CellContentDoubleClick Occurs when the user double click on a cell
contents.
CellEnter Occurs when the currents cell recieves input
focus.
16
grd1.DataSource = dt;
“OR”
grd1.DataSource = ds.Tables[0] ;
“OR”
grd1.DataSource = ds ;
grd1.DataMembers = ds.Tables[0].TableName;
“OR”
grd1.DataSource = ds ;
grd1.DataMember = “student” ;
“OR”
“OR”
17
grd1.DataBindings.Add("DataSource",ds,ds.Tables[0].TableNam
e);
using System;
18
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication10
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=desktop; database=student; integrated
security=sspi");
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter da = new SqlDataAdapter("Select * from marks_details", con);
if (ds.Tables.Contains("marks") == true)
{
ds.Tables.Remove("marks");
}
da.Fill(ds, "marks");
grd1.DataSource = ds.Tables["marks"];
}
private void button2_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Select * from stud", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (ds.Tables.Contains("details") == true)
{
ds.Tables.Remove("details");
}
ds.Load(dr, LoadOption.Upsert, "details");
grd1.DataSource = ds.Tables["details"];
con.Close();
}
}
}
Example of DataBinding with TextBox
If we want to add a TextBox control to a form and bind it to a column of a
table in a DataSet, the control is going to communicate with the
BindingContext object for this . The BindingContext object is going to
talk to the specific CurrencyManager object for the data the TextBox
control is binding.
19
using System;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication9
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Server=desktop; database=student; integrated
security=sspi");
SqlDataAdapter da;
DataSet ds = new DataSet();
CurrencyManager cm;
public Form1()
{
InitializeComponent();
}
cm = (CurrencyManager)BindingContext[ds, ds.Tables[0].TableName];
vsb.Maximum = cm.Count - 1;
vsb.Minimum = 0;
}
private void btn_first_Click(object sender, EventArgs e)
{
//BindingContext[ds, "marks"].Position = 0;
cm.Position = 0;
vsb.Value = cm.Position;
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
button4.Enabled = true;
}
private void btn_next_Click(object sender, EventArgs e)
{
button1.Enabled = true;
button2.Enabled = true;
cm.Position ++;
//BindingContext[ds, "marks"].Position = BindingContext[ds, "marks"].Position + 1;
vsb.Value = BindingContext[ds, "marks"].Position;
if (BindingContext[ds, "marks"].Count-1 == BindingContext[ds, "marks"].Position)
{
button3.Enabled = false;
button4.Enabled = false;
}
}
private void btn_prev_Click(object sender, EventArgs e)
{
button3.Enabled = true;
button4.Enabled = true;
cm.Position --;
//BindingContext[ds, "marks"].Position = BindingContext[ds, "marks"].Position - 1;
vsb.Value = BindingContext[ds, "marks"].Position;
if (BindingContext[ds, "marks"].Position==0)
{
button1.Enabled = false;
button2.Enabled = false;
}
}
private void btn_last_Click(object sender, EventArgs e)
{
cm.Position = cm.Count - 1;
//BindingContext[ds, "marks"].Position = BindingContext[ds, "marks"].Count - 1;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
button4.Enabled = false;
21
vsb.Value = cm.Position;
}
private void vsb_Scroll(object sender, ScrollEventArgs e)
{
cm.Position = vsb.Value;
//BindingContext[ds, ds.Tables[0].TableName].Position = vsb.Value;
if (vsb.Value == 0)
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
button4.Enabled = true;
}
if (vsb.Value == cm.Count-1)
{
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
button4.Enabled = false;
}
if (vsb.Value > 0 && vsb.Value <cm.Count- 1)
{
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
}
}
}
}
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
static String path = "";
SqlConnection con = new SqlConnection("Server=desktop; database=student;
Integrated Security=sspi");
public Form1()
{
InitializeComponent();
}
private void form1_Load(Object sender , EventArgs e)
{
Bitmap b = new Bitmap(200,200);
b.Save("c:\\pict1.jpg");
Path="c:\\pict1.jpg";
}
private void btn_display_Click(object sender, EventArgs e)
{
dataGridView1.RowTemplate.Height = 150;
dataGridView1.AutoSizeColumnsMode= DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.AllowUserToAddRows = false;
dataGridView1.ReadOnly = true;
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter("Select * from stud_info", con);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
cmd.ExecuteNonQuery();
24
MessageBox.Show("Inserted");
con.Close();
}
(i) First of all we have to drag and drop two textbox,two label,two
button,one picturebox and two “openfiledialog” control on the form.
(ii) Right click on the any tab of “toolbox” and select “choose Items”
menu as :--
26
(iii) Then we find a new window for adding the new control in toolbox as:--
(iv) Select the “Windows Media Player” and click on the “OK” button.
(v) Drag and drop “Windows Media Player” control from “toolbox” on the Form as :--
using System.Data.SqlClient;
using System.IO;
(ix) Double click on the picturebox and edit the code as :--
(x) Double click on the “Select Sound file” button and edit the code as :
cmd.Parameters.AddWithValue("@roll",textBox1.Text);
cmd.Parameters.AddWithValue("@nm", textBox2.Text);
cmd.Parameters.AddWithValue("@img", data);
cmd.Parameters.AddWithValue("@sound", snd);
cmd.Parameters.AddWithValue("@ext", ext);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("saved");
}
(xiii) Double click on the roll textbox and edit the code as :
File.WriteAllBytes("c:\\sound\\img.jpg", img);
pictureBox1.ImageLocation = "c:\\img.jpg";
File.WriteAllBytes("c:\\sound\\snd1."+ext, snd);
axWindowsMediaPlayer1.URL = "c:\\sound\\snd1."+ext;
}
else
{
textBox2.Text = "";
pictureBox1.ImageLocation = "";
}
}
catch(Exception ex)
{
MessageBox.Show("" + ex);
}
}
(ii) Double click on the roll TextBox and edit the code as :
(iii) Double click on the Save button and edit the code as :
txt_roll.Clear();
txt_roll.Focus();
}
(iv) Double click on the update button and edit the code as :
private void btn_update_Click(object sender, EventArgs e)
{
SqlDataAdapter da=new SqlDataAdapter("select * from stud_info where roll='" +
txt_roll.Text + "'", con);
//"OR"
dt.Rows[0][0] = txt_roll.Text;
dt.Rows[0][1] = txt_nm.Text;
dt.Rows[0][2] = txt_add.Text;
dt.Rows[0][3] = txt_ph.Text;
da.Update(dt);
dt.AcceptChanges();
MessageBox.Show("Successfully updated");
}
(v) Double click on the delete button and edit the code as :
Note : The “Roll” column must be set as the primary key in database table.
31
Note: The TableDirect values use only into MS Access database for display the record..
Note :If we want to delete the procedure then we have to write as:---
using System;
using System.Data.SqlClient;
namespace storedprocedure
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india;database=student;integrated
security=sspi");
}
}
}
using System;
using System.Data.SqlClient;
namespace storedprocedure
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india\\ranjit;
database=student;integrated security=sspi");
public Form1()
{
InitializeComponent();
}
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
namespace storedprocedure
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india\\ranjit;
database=student;integrated security=sspi");
public Form1()
{
InitializeComponent();
}
using System;
using System.Data.SqlClient;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Server=india\\ranjit; database=student;integrated security=sspi");
}
}
}
35
namespace WindowsApplication6
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("Server=india\\ranjit; database=student; integrated
security=sspi");
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("selected index = "+comboBox1.SelectedIndex.ToString());
MessageBox.Show("Selected value= "+comboBox1.SelectedValue.ToString());
MessageBox.Show("Selected Item= "+comboBox1.SelectedItem.ToString());
MessageBox.Show("Selected text= "+comboBox1.SelectedText.ToString());
}
}
}
}
36
Output Will be as :
using System;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Threading;
namespace WindowsApplication7
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india\\ranjit; database=student; integrated security=sspi");
Font f20 = new Font("", 20, FontStyle.Bold);
Font f11 = new Font("",11, FontStyle.Regular);
int row, col;
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.RowTemplate.Height = 30;
SqlDataAdapter da = new SqlDataAdapter("Select * from stud_info", con);
DataSet ds = new DataSet();
da.Fill(ds, "stud");
dataGridView1.DataSource = ds.Tables[0];
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
Random rand = new Random();
int r=rand.Next(1, 255);
int g = rand.Next(1, 255);
int b = rand.Next(1, 255);
Thread.Sleep(50);
col.DefaultCellStyle.BackColor = Color.FromArgb(r, g, b);
}
}
private void dataGridView1_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex >= 0 && e.RowIndex>=0)
{
row = e.RowIndex;
col = e.ColumnIndex;
dataGridView1[e.ColumnIndex, e.RowIndex].Style.Font = f20;
}
}
private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
dataGridView1[col,row].Style.Font = f11;
}
}
}
38
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication11
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection("server=india\\ranjit; database=student; integrated
security=sspi");
}
}
(ii) Then have to write the code on Click event of button1 as :----
Note 1 : Here Connection is not necessary for displaying data from xml file.
Step 2 : If server explorer window has not available then select menu view server
explorer or by pressing Ctrl + W , S.
Step 3 : Right click on Data Connection option in the server explorer. Window.
40
Step 4 : Select Add Connection item. Then display the window as below
Step 5 : Double Click on Microsoft SQL Server or click on Continue Button then display the
as :----
41
Step 6 : Type Server Name of SQL Server and then select database.
(ii) Click on Right Top Corner on Triangle Symbol of the DataGridView control
(iv) Expand the Choose Data Source Combo box then find the window as :----
(iv) Click on Add Project Data Source then display the window as:----
42
(vi) Choose or select data connection name in the combo box and click on Next Button.
Transaction: ALL or Nothing ---- this is the main feature of a transaction. When writing a
few records then either all are written or every thing will be undone. If there is just one failure
when writing one records, all the other things that are done within the transaction are rollback.
Transactions are commonly used with database, but we can also perform
transactions on volatile in memory based objects such as list of objects. With a list that supports
transactions, if an object is added or removed and the transaction fails, the list action is
automatically undone.
Example:
class OleDbConnectionOracle
{
public static void Main()
{
string connectionString = "provider=MSDAORA;data source=ORCL;user
id=SCOTT;password=TIGER";
OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);
myOleDbConnection.Open();
myOleDbDataReader.Read();
myOleDbDataReader.Close();
myOleDbConnection.Close();
}
}
Ans:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
45
SqlDataAdapter da;
SqlCommandBuilder builder;
DataTable dt;
CurrencyManager cm;
databinding();
}
dt.NewRow();
dt.Rows.Add(textBox1.Text, textBox2.Text);
da.Update(dt);
dt.AcceptChanges();
cm.Position++;
MessageBox.Show("Record saved");
}
{
con.Open();
SqlCommand cmd = new SqlCommand("Delete from stud where roll='" +
textBox1.Text + "'", con);
cmd.ExecuteNonQuery();
con.Close();
databinding();
MessageBox.Show("Record Deleted");
}
public void databinding()
{
da = new SqlDataAdapter("Select * from stud", con);
dt = new DataTable("stud");
builder = new SqlCommandBuilder(da);
da.Fill(dt);
textBox1.DataBindings.Clear();
textBox2.DataBindings.Clear();
(iii) Double click on the button and edit the code as :--
(iv) After editing the above code we have to execute the program and click on the
button for creating the “xml” file.
(v) Select the menu “projectAdd windows FormCrystal ReportAddOkCreate
new Connection Database Files Select our xml file in c: drive click on
the button finish “.
(vi) Expand the “Database fields” and Tables in “Field Explorer” window.
(vii) Drag and drop All Columns from “Field Explorer” window in the “Details
section” of the Crystal Report page as our requirements. For Example…
(viii) After Designing the Crystal Report Page Again we have to double click on the button and
append the code as :
(iv) Press F5 key then click on the Button for creating the “.xsd” file in “C:” drive.
(v) Now add “Data.xsd” file in our project by Right click on the project in Solution Explorer,
then select “Add Existing Item” and then browse for “Data.xsd” file in “C:” drive and
add it to the project.
(vi) Now select the menu “ProjectAdd Windows
FormReportingReportAdd” then we find a “Report1.rdlc” file with
“Report Data” explorer window.
(vii) Right click on the “DataSets” in “Report Data” window then click on the “Add
DataSet” then we find a new window then select DataSource name in the
combobox as “NewDataSet” and click on “OK” button as:-
(viii) Now right click within “Report1.rdlc” file then select “InsertTable” then we
find a table by three columns and one rows.
(ix) Drag and drop our required columns from “Report
DataDataSetsDataSet1” within table as :-
(x) We can also add Page Header, Page Footer and Sets the background,
foreground, Font etc property of our report.
(xi) Now Again double click on the Button in “Form1” and append the code as:
reportViewer1.LocalReport.ReportPath ="c:\\users\\ranjit\\
50
reportViewer1.LocalReport.DataSources.Clear();
reportViewer1.LocalReport.DataSources.Add(new
Microsoft.Reporting.WinForms.
ReportDataSource("DataSet1", dt));
reportViewer1.RefreshReport();
}
using System.Data.OleDb;
51
Note:
(a) HDR=Yes; means it allows the first row of
excel sheet is display in the Heading;
(vi) Double click on the Button and edit the code as :--
(iv) Double click on the Save Button and edit the code as :--
“OR”
53
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Successfully saved");
}
PASSWORD = ‘’”
OdbcConnection odbcCon = new odbcConnection(myConnectionString)
(xii) Select the “Browse” Tab in opened window and chose the file in following
location : -- “C:\Program Files\Common Files\System\Ole DB\
oledb32.dll”
(xiii) Again Select the menu “Project ( Add Reference” and select “adodb” in
the “.NET” tab.
(xiv) Write the the code in top of the file as:--
“ Using System.Collections; ”
(xv) And Below Write the code as:--
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
createDatabase();
}
private void createDatabase()
{
MSDASC.DataLinks dataLinks = new MSDASC.DataLinksClass();
ADODB.Connection cs = (ADODB.Connection)dataLinks.PromptNew();
cs.Open("", "", "", 0);
object missing = null;
string database = "SetupTestDatabase";
cs.Execute("create database " + database, out missing, 0);
cs.DefaultDatabase = database;
String comma = "create table ranjit_test(name varchar(50),
phone varchar(15))";
cs.Execute(comma, out missing, 0);
}
(xvii) Choose “Setup and deployment ( Setup project” in the opened window.
(xviii) Click on “Custom Action” Icon in the “top and Right position” of the
“Solution Explorer” window.
(xix) Right Click on “Install” and select “Add Custom Action” then Choose
“Application Folder” in the combobox and click on “ Add Ouput” button.
As in Below Figure:---
((
(xxvii) Type “Server name” select “Use Windows NT………” and click in ok
button not type any database name. as ----
58
(xxviii) Now we have found the in sql server automatically created one
database and one table.
using System.Management;
namespace WindowsApplication24
{
public partial class Form1 : Form
{
private void btn_shutdown_Click(object sender, EventArgs e)
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass
("Win32_OperatingSystem");
mcWin32.Get();
// You can't shutdown without security privileges
59
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams =
mcWin32.GetMethodParameters("Win32Shutdown");
// Flag 1 means we want to shut down the system
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown",
mboShutdownParams, null);
}
}
}
}