1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| 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) { if (!this.IsPostBack) { BindGrid(); } }
private DataTable ReadGridView() { DataTable dt = new DataTable(); DataRow dr; dt.Columns.Add(new DataColumn("ProductID", typeof(string))); dt.Columns.Add(new DataColumn("ProductName", typeof(string))); dt.Columns.Add(new DataColumn("CategoryID", typeof(string))); for (int i = 0; i < this.GridView1.Rows.Count; i++) { dr = dt.NewRow(); dr[0] = this.GridView1.Rows[i].Cells[0].Text.Trim(); dr[1] = this.GridView1.Rows[i].Cells[1].Text.Trim(); dr[2] = this.GridView1.Rows[i].Cells[2].Text.Trim(); dt.Rows.Add(dr); } return dt; } protected void Button1_Click(object sender, EventArgs e) { DataTable dt = ReadGridView(); //this.GridView1.DataSource = dt; //this.GridView1.DataBind(); DataRow row = dt.NewRow(); row.ItemArray = new object[] { "oec2003", "oec2003", "oec2003" }; dt.Rows.InsertAt(row, 0); dt.AcceptChanges(); this.GridView1.DataSource = dt; this.GridView1.DataBind(); }
private void BindGrid() { string str = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString(); using (SqlConnection con = new SqlConnection(str)) { SqlCommand cmd = new SqlCommand("SELECT top 1 [ProductID], [ProductName], [CategoryID] FROM [Products]", con); SqlDataAdapter sda = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); sda.Fill(ds); this.GridView1.DataSource = ds.Tables[0].DefaultView; this.GridView1.DataBind(); sda.Dispose(); ds.Dispose(); }
} }
|