Tehrik-e-Insaaf

Earn 600$ by Clicking on each Ad

GoWellUp.com

Wednesday, October 22, 2008

How to change the default form in windows application in c#.net

Go to Program.cs of your application and replace the form name with your form name in Application.Run

Example

Application.Run(new MainForm());

How to fill the datagrid with the data from database using datasets

1. Make connection String and selection statement
SqlConnection conn = new SqlConnection(@"Data Source=192.125.5.1;Initial Catalog=Test;User ID=sa;Password=sa;");
string getCommand = @"select * from dbo.compDetails";

2. Declare the object of command & give the respective parameters
//give selection statement
SqlCommand cmd = new SqlCommand(getCommand);
//give the command type
cmd.CommandType = CommandType.Text;
//give connection object
cmd.Connection = conn;

3. Declare the object of SqlDataAdpater & give command object
SqlDataAdapter da = new SqlDataAdapter(cmd);

4. Declare the object of dataset as container of data
DataSet ds = new DataSet();

5. Open the connection
conn.Open();

6. Fill the object of data Adapter with dataset object
da.Fill(ds, "dbo.complaints");

7. Provide the dataset object as a source to dataGrid
this.dataGrid1.DataSource = ds.Tables[0];

8. Close the connection
conn.Close();


Example:

public void getData()
{
SqlConnection conn = new SqlConnection(@"Data Source=192.125.5.1;Initial Catalog=Test;User ID=lrmis;Password=lrmis;");
string getCommand = @"select * from dbo.compDetails";
SqlCommand cmd = new SqlCommand(getCommand);
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds, "dbo.complaints");
this.dataGrid1.DataSource = ds.Tables[0];
conn.Close();
}

How to Insert Data in Database in c#

1. First of all make connection string
string connString="Data Source=databasename;Initial Catalog=Test;User ID=sa;Password=sa;"
SqlConnection conn = new SqlConnection(connString);

2. Open the connection
conn.Open();

3. Write the insert command
string insertCommand= @"insert into dbo.compDetails(OwnerId, compName, compAddress, compPhone) values('" + compId + "','" + this.txtCompaName.Text + "','" + this.txtCompAddress.Text + "','" + this.txtCompPhone.Text + "')";

SqlCommand cmdInsert = new SqlCommand(insertCommand, conn);

4. Execute the command
cmdInsert.ExecuteScalar();

5. Close the connection
conn.Close();


Example:

public void setData()
{

string connString="Data Source=databasename;Initial Catalog=Test;User ID=sa;Password=sa;"
SqlConnection conn = new SqlConnection(connString);
conn.Open();
Guid compId = Guid.NewGuid();
string insertCommand= @"insert into dbo.compDetails(OwnerId, compName, compAddress, compPhone) values('" + compId + "','" + this.txtCompaName.Text + "','" + this.txtCompAddress.Text + "','" + this.txtCompPhone.Text + "')";
SqlCommand cmdInsert = new SqlCommand(insertCommand, conn);
cmdInsert.ExecuteScalar();
conn.Close();

}