using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//1.sqlclient
using System.Data;
using System.Data.SqlClient;
//2.webconfig
using System.Web.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
string str_name = "";
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
//conn.ConnectionString = "Data Source=DESKTOP-E13HKV7\APM2014;Initial Catalog=weberp;Persist Security Info=True;User ID=sa;Password=~1qaz";
//3.設定SqlConnection
conn.ConnectionString = WebConfigurationManager.ConnectionStrings["dbconn"].ConnectionString.ToString();
conn.Open();
//4.設定command
cmd.Connection = conn;
cmd.CommandText = "SELECT mname FROM sys_user where mpassword = @mpassword";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@mpassword", TextBox1.Text);
//5.slect會回傳值時,SqlDataReader
//SqlDataReader dr = cmd.ExecuteReader();
//if (dr.HasRows)
//{
// //判斷dr.read()若沒讀到值會回傳false
// while (dr.Read())
// {
// str_name += dr["mname"].ToString() + "<br />";
// }
//}
//dr.Close();
//5-2無回傳值時,insert,update,delete
//cmd.ExecuteNonQuery();
//5-1.Dataset
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
//if (dt.Rows.Count > 0)
//{
// //6.寫法1
// //for (int i = 0; i <dt.Rows.Count; i++)
// //{
// // str_name += dt.Rows[i]["mname"].ToString()+"<br />";
// //}
// //7.寫法2
// foreach (DataRow dr_name in dt.Rows)
// {
// str_name += dr_name["mname"].ToString() + "<br />";
// }
//}
//if (str_name == "")
//{
// Literal1.Text = "查無資料";
//}
//else
//{
// Literal1.Text = str_name;
//}
//9.事後多加一筆資料利用dt的NewRow()方法產生一筆新的DataRow
DataRow dr = dt.NewRow();
dr["mname"] = "tony";
dt.Rows.Add(dr);
//8.結合Gridview
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
沒有留言:
張貼留言