วันพุธที่ 4 กรกฎาคม พ.ศ. 2550

C# Connect DB

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;


public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void BtnInsert_Click(object sender, EventArgs e)
{
string txtName = TextBox2.Text;
string txtLname = TextBox3.Text;
string txtEmail = TextBox4.Text;
string txtPhone = TextBox5.Text;
string txtUserName = TextBox6.Text;
string txtPassword = TextBox7.Text;
string txtWebSite = TextBox8.Text;

string StrConn = "Database=work; server=localhost; user id = sa; password = 1234";
string StrSql = "INSERT INTO tbPersonalinfo(Name, Lname, Email, Phone, UserName, Password, WebSite) " +
"VALUES ('" +
txtName + "', '" +
txtLname + "', '" +
txtEmail + "', '" +
txtPhone + "', '" +
txtUserName + "', '" +
txtPassword + "', '" +
txtWebSite + "')";

SqlConnection conn = new SqlConnection(StrConn);
conn.Open();
SqlCommand cmd_sql = new SqlCommand(StrSql, conn);
int rowRetun = cmd_sql.ExecuteNonQuery();
Console.WriteLine("{0} row Retuned", rowRetun);
//TextBox1.Text = rowRetun;
conn.Close();
}
protected void BtnSelect_Click(object sender, EventArgs e)
{
string StrConn = "Database=work; server=localhost; user id = sa; password = 1234";
SqlConnection conn = new SqlConnection(StrConn);

string SqlCmd = "SELECT ID, Name, Lname, Email, Phone, UserName, Password, WebSite FROM tbPersonalinfo ORDER BY ID DESC";
SqlDataAdapter da = new SqlDataAdapter(SqlCmd, conn);
DataSet ds = new DataSet();

da.Fill(ds, "emps");
GdvListData.DataSource = ds;
GdvListData.DataBind();
}
}