gridview快速添加行,删除行和修改行

发布时间: 2007-01-26 09:47    作者: 未知    来源: 未知    浏览:    评论

以前看到很多人在网上说要关于gridview的资料  现在我把用于编辑,修改的东西贴出来

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
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 charge : System.Web.UI.Page
{
    
protected SqlCommand com;
    
protected SqlDataReader reader;
    
protected SqlConnection con;
    
protected SqlDataAdapter da;
    
protected DataSet ds;
    
protected string sql, strsql, var_strsql;
    DataTable myTable;
    DataColumn col;
    Int32 i 
= 0;

    
protected void Page_Load(object sender, EventArgs e)
    
{

        
if (!IsPostBack)
        
{
            
if (Request.QueryString["action"== "edit")
            
{
                lbID.Text 
= Request.QueryString["id"];
                show();
                show1.Visible 
= false;
                show2.Visible 
= false;
                show3.Visible 
= false;
                data.Visible 
= false;
                btn_ok.Text 
= "修改";
                txt_pi.Focus();
                btn_ok.Attributes.Add(
"onclick""javascript: return confirm('你確定要修改嗎?');");
            }

            
else
            
{
                lbl_sql.Text 
= "select * from charge";
                data.DataSource 
= CreateNewDataSource();
                data.DataBind();
                txt_pi.Focus();

            }


        }

    }


    
Web 窗体设计器生成的代码





    
protected void init_text()
    
{
        txt_pi.Text 
= "";
        txt_des.Text 
= "";
        txt_cou.Text 
= "";

    }


    
protected void Add1_Click(object sender, EventArgs e)
    
{
        
if (txt_pi.Text.Trim() != "")
        
{
            data.DataSource 
= CreateDataSource();
            data.DataBind();
            init_text();
            
this.txt_pi.Focus();
        }


        
else
        
{
            Response.Write(
"<Script>alert("PI編號不能为空");</Script>");

        }


    }


    System.Collections.ICollection CreateNewDataSource()  
//建立内存数据库
    {
        DataTable myTable 
= new DataTable("myTable");
        col 
= myTable.Columns.Add("row"typeof(Int32));
        col 
= myTable.Columns.Add("pi"typeof(string));
        myTable.Columns.Add(
"remark"typeof(string));
        myTable.Columns.Add(
"charge"typeof(string));
        ViewState[
"myTable"= myTable;
        DataView myView 
= new DataView(myTable);
        
return myView;
    }


    System.Collections.ICollection CreateDataSource()
    
{

        
if (ViewState["myTable"!= null)    //实例化myTable
        {
            myTable 
= (DataTable)ViewState["myTable"];
        }

        DataRow NewRow 
= myTable.NewRow();
        Session[
"i"= System.Convert.ToInt32(Session["i"]) + 1;
        NewRow[
"row"= System.Convert.ToInt32(Session["i"]);
        NewRow[
"pi"= " " + txt_pi.Text.Trim();
        NewRow[
"remark"= " " + txt_des.Text.Trim();
        NewRow[
"charge"= " " + txt_cou.Text.Trim();

        myTable.Rows.Add(NewRow);
        ViewState[
"myTable"= myTable;
        DataView myView 
= new DataView(myTable);
        
//myView.Sort = "modu_id";    //数据排序
        return myView;
    }



    
protected void data_RowCommand(object sender, GridViewCommandEventArgs e)
    
{
        
if (e.CommandName == "select")   //单击编辑按钮时发生的事件
        {

            
int index = Convert.ToInt32(e.CommandArgument);

            txt_row.Text 
= Convert.ToString(index + 1);
            txt_pi.Text 
= " " + data.Rows[index].Cells[1].Text.ToString().Trim();
            txt_des.Text 
= " " + data.Rows[index].Cells[3].Text.ToString().Trim();
            txt_cou.Text 
= " " + data.Rows[index].Cells[2].Text.ToString().Trim();


        }

    }

    
protected void edit_Click(object sender, EventArgs e)
    
{
        
if (ViewState["myTable"!= null)
            myTable 
= (DataTable)ViewState["myTable"];
        DataRow[] rowfind 
= myTable.Select("row ='" + txt_row.Text.Trim() + "'");
        
if (rowfind.Length > 0)
        
{
            rowfind[
0]["pi"= txt_pi.Text.Trim();
            rowfind[
0]["remark"= txt_des.Text.Trim();
            rowfind[
0]["charge"= txt_cou.Text.Trim();
        }

        ViewState[
"myTable"= myTable;
        data.DataSource 
= myTable.DefaultView;                       //将ds对象中的表邦定到DataList控件
        data.DataBind();
        init_text();
    }

    
protected void data_RowCreated(object sender, GridViewRowEventArgs e)
    
{
        
//e.Row.Cells[0].Attributes.Add("onclick", "return confirm('您是否确定要删除这条信息');"); 
    }

    
protected void del_Click(object sender, EventArgs e)
    
{

        
if (ViewState["myTable"!= null)
            myTable 
= (DataTable)ViewState["myTable"];
        DataRow rowindex 
= myTable.Rows[i];
        DataRow[] rowfind 
= myTable.Select("row='" + txt_row.Text.Trim() + "'");
        rowfind[
0].Delete();
        ViewState[
"myTable"= myTable;
        
for (int x = 0; x < myTable.Rows.Count; x++)
        
{
            rowindex 
= myTable.Rows[x];
            rowindex[
"row"= x + 1;
        }

        data.DataSource 
= myTable.DefaultView;                       //将ds对象中的表邦定到DataList控件
        data.DataBind();
    }

    
protected void show()
    
{
        
string a = Request.QueryString["id"];
        
//lbl1.Text = Request.QueryString["action"];
        btn_ok.Text = "修改";
        SqlConnection con 
= DBCon.creatConnection();        //連接資料源
        string strSql = "select * from count_gs where id='" + a + "'";
        con.Open();
        com 
= new System.Data.SqlClient.SqlCommand(strSql, con);    //對資料庫的查詢、對存儲過程的調用、返回特定表的直接請求
        SqlDataAdapter my = new SqlDataAdapter(strSql, con);  //DataAdapter物件充當資料庫和ADO.NET物件模型中斷開連接的物件之間的橋梁
        DataTable tbl = new DataTable();   //一旦從資料庫中讀出資料,並將其存在DataTable中,資料與伺服器的連接就斷開

        
//my.SelectCommand = com;   //指定命令物件以便從資料存儲區檢索行
        my.Fill(tbl);         //通過DataAdapter物件的Fill方法,把查詢的結果存在DataTable中
        DataRow row = tbl.Rows[0];
        txt_pi.Text 
= System.Convert.ToString(row["pi"]).Trim();
        txt_des.Text 
= System.Convert.ToString(row["remark"]).Trim();
        txt_cou.Text 
= System.Convert.ToString(row["charge"]).Trim();


    }


    
protected void btn_ok_Click(object sender, EventArgs e)
    
{

        
if (Request.QueryString["action"== "add")
        
{
            
if (ViewState["myTable"!= null)
                myTable 
= (DataTable)ViewState["myTable"];
            
foreach (DataRow row in myTable.Rows)
            
{
                
string tt = Session["userID"].ToString();
                
string addsql = "insert into count_gs(pi,remark,charge,last_update_by,last_update_date) values('" + row["pi"+ "','" + row["remark"].ToString() + "','" + row["charge"].ToString() + "','" + tt + "','" + DateTime.Now.ToShortDateString() + "')";
                
// Response.Write(addsql);
                SqlConnection con = DBCon.creatConnection();
                con.Open();
                com 
= new System.Data.SqlClient.SqlCommand(addsql, con);
                com.ExecuteNonQuery();
                com.Dispose();
                con.Close();
            }

            Response.Write(
"<Script>alert("保存完成");</Script>");
            init_text();
            data.DataSource 
= CreateNewDataSource();
            data.DataBind();
        }

        
else
        
{
            
string td = Session["userID"].ToString();
            SqlConnection con 
= DBCon.creatConnection();        //實例物件資料庫連接物件con
            con.Open();
            
string sql = "UPDATE count_gs SET pi='" + txt_pi.Text.ToString().Trim() + "',remark='" + txt_des.Text.ToString().Trim() + "',charge='" + txt_cou.Text.ToString().Trim() + "',last_update_by='" + td + "',last_update_date='" + DateTime.Now.ToString() + "' where id='" + Request.QueryString["id"+ "'";
            
//Response.Write(sql);
            com = new System.Data.SqlClient.SqlCommand(sql, con);
            com.ExecuteNonQuery();
            com.Dispose();                          
//釋放com物件佔用的資源
            con.Close();
            Response.Write(
"<Script>alert("記錄已修改");</Script>");
            show();
        }


    }


}





<%@ Page Language="C#" AutoEventWireup="true" CodeFile="charge.aspx.cs" Inherits="charge" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    
<title>实值資訊</title>
    
<link href="../Css/pubstyle.css" rel="stylesheet" type="text/css">
     
<script language="javascript" src="../js/function.js" type="text/javascript"></script>
    
<style>
      .navPoint 
{CURSOR: hand; FONT-FAMILY: Webdings; FONT-SIZE: 7pt}
    
</style> 
    
</head>
<%--<script language=javascript type="text/javascript">
function check()
{
 var matname
=String(document.form1.matName.value);
&