天涯之外

导航

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

以前看到很多人在网上说要关于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);
 var spec
=String(document.form1.SpecNo.value);
 
if (matname.length==0 || spec.length==0)
 
{

   window.alert(
"原料分類或規格為空請填寫完整");
  
return false;
   
 }

}

</script>--%>
<body>
    
<form id="form1" runat="server">
    
<TABLE width="100%" align="center" style="z-index: 100; left: 0px; position: absolute; top: 0px">
    
<TR style="background-color="> 
        
<TD colspan="3" valign="baseline" style="height: 33px; width: 629px;">
            
&nbsp; &nbsp; &nbsp; &nbsp;
        IDEAL实值資訊
           
            
<asp:Label ID="lbl_sql" runat="server" Style="z-index: 102; left: 224px; position: absolute;
                top: 8px" Width="322px" Visible="False"></asp:Label>
        <IMG src="../images/add.gif" width="32" height="32" align="absBottom" style="left: -169px; position: relative; top: 1px"></TD>
        
<TD  valign="baseline" style="height: 33px; width:50px;">
            
<DIV align="right"> 
          
<!--    返回按鈕    -->
          
<a href="javascript:window.close()"><img src="../images/close.gif" width="72" height="15" hspace="20" border="0"></a>&nbsp;</DIV>
          
</TD>
    
</TR>
    
            
<TR id="frmTop"> 
            
<td colspan="4">
            
<table width="100%">
                
<tr>
                    
<td class="border-bgcolor" style="width: 14%; height: 22px; text-align: right">
                        
&nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; PI編號:</td>
                    
<td class="border-bgcolor" style="width: 25%; height: 22px; text-align: left">
                        
<asp:TextBox ID="txt_pi" runat="server" onfocus="fos(this)" onblur="blu(this)" onkeydown="return checkKey()"></asp:TextBox></td>
                    
<td class="border-bgcolor" style="width: 14%; height: 22px; text-align: center">
                    
</td>
                    
<td class="border-bgcolor" style="width: 25%; height: 22px; text-align: center">
                    
</td>
                
</tr>
         
            
<tr>
                
<td class="border-bgcolor" style="width: 14%; height: 21px; text-align: right">
                    收費敘述:
</td>
                
<td class="border-bgcolor" style="width: 25%; height: 21px; text-align: left">
                    
<asp:TextBox ID="txt_des" runat="server" onfocus="fos(this)" onblur="blu(this)" onkeydown="return checkKey()"></asp:TextBox></td>
                
<td class="border-bgcolor" style="width: 14%; height: 21px; text-align: right">
                    收費:
</td>
                
<td class="border-bgcolor" style="width: 25%; height: 21px; text-align: left">
                    
<asp:TextBox ID="txt_cou" runat="server" onfocus="fos(this)" onblur="blu(this)" onkeydown="return checkKey()"></asp:TextBox></td>
               
</TR>
                
<tr>
                    
<td class="border-bgcolor" style="width: 14%; height: 25px; text-align: right">
                        
</td>
                    
<td class="border-bgcolor" style="width: 25%; height: 25px; text-align: left">
                        
</td>
                    
<td class="border-bgcolor" style="width: 14%; height: 25px; text-align: right">
                        
</td>
                    
<td class="border-bgcolor" style="width: 25%; height: 25px; text-align: left">
                        
</td>
                
</tr>
                
<tr>
                    
<td class="border-bgcolor" style="width: 14%; height: 25px; text-align: right">
                        
</td>
                    
<td class="border-bgcolor" style="width: 25%; height: 25px; text-align: left">
                        
</td>
                    
<td class="border-bgcolor" style="width: 14%; height: 25px; text-align: right">
                        
</td>
                    
<td class="border-bgcolor" style="width: 25%; height: 25px; text-align: left">
                        
</td>
                
</tr>
              
                
<tr id="show3" runat="server">
                    
<td class="border-bgcolor" colspan="4" style="height: 25px">
                       
<DIV align="right">
                       
<asp:TextBox ID="txt_row" runat="server" Width="24px" Visible="False"></asp:TextBox>
                     
<asp:Button class="ButtonCss" id="Add1"   runat="server" Text="增加行" BorderWidth="1px" OnClick="Add1_Click" Width="70px"></asp:Button>
                     
<asp:Button class="ButtonCss" id="edit"   runat="server" Text="修改行" BorderWidth="1px" OnClick="edit_Click" Width="70px"></asp:Button>
                     
<asp:button class="ButtonCss" id="del"  runat="server" Text="刪除行" Width="70px" OnClick="del_Click"></asp:button>&nbsp;
                        
</DIV>
                    
</td>
                    
                  
                
</TR>
                
</table>
                
</td>
                
</tr>
                
                
<!--垂直分割條-->
        
<tr id="show2" runat="server">
        
<td colspan="4" bgColor=#a8cbf1 onclick="switchTopBar()" align="center" style="height: 1px">
        
<span class="navPoint" id="switchPoint_Top" title="垂直分割條"><font color="#000000">5</font></span>
        
</td>
        
</tr>
        
<tr id="show1" runat="server">
           
<td bgColor="#f0f0f0" colspan="5" style="height: 9px">实值列表</td>
        
</tr>
        
<TR> 
          
<td colspan="4" vAlign="top" align="right" style="height:20px">
          
<!--GridView style-->
          
<asp:GridView ID="data" runat="server" BackColor="White" BorderColor="Blue"
            BorderStyle
="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None" Width="100%" AutoGenerateColumns="False" CaptionAlign="Top" ForeColor="Blue"  OnRowCommand="data_RowCommand" OnRowCreated="data_RowCreated"   >
            
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
            
<RowStyle Font-Size="8pt" Font-Names="Arial" HorizontalAlign="Center" ForeColor="Black" BackColor="Lavender" />
            
<SelectedRowStyle Font-Size="8pt" Font-Names="Arial" HorizontalAlign="Center" ForeColor="Black" BackColor="#6699cc"/>
            
<AlternatingRowStyle  Font-Size="8pt" Font-Names="Arial" HorizontalAlign="Center" ForeColor="Black" BackColor="White"/>
            
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
            
<HeaderStyle Font-Size="9pt" Height="10%" Font-Names="Arial" Font-Bold="True" HorizontalAlign="Center" ForeColor="Black"
              BorderColor
="White" BackColor="Beige" />
            
<Columns>
                
            
                
                
<asp:ButtonField DataTextField="row" CommandName="select" HeaderText="行號" >
                                    
<ItemStyle ForeColor="orange" Width="10%" />
                                
</asp:ButtonField>
                
<asp:BoundField DataField="pi" HeaderText="PI編號" SortExpression="pi" >
                    
<ItemStyle Width="15%" />
                
</asp:BoundField>
                
<asp:BoundField DataField="charge" HeaderText="收費" SortExpression="charge" >
                    
<ItemStyle Width="15%" />
                
</asp:BoundField>
                                
<asp:BoundField DataField="remark" HeaderText="收費敘述" SortExpression="remark" >
                    
<ItemStyle Width="15%" />
                
</asp:BoundField>
               
</Columns>
            
<EmptyDataRowStyle Height="20px" VerticalAlign="Top" />
            
<EditRowStyle Height="20px" />
        
</asp:GridView>
        
</td>
        
</TR>
        
<tr>
        
<td colspan="4" align="center" style="height: 22px">
            
<asp:Label ID="lbID" runat="server" Style="position: relative" Text="Label" Visible="False"></asp:Label>
        
<asp:button class="ButtonCss" id="btn_ok"  runat="server" Text="保 存"  Width="70px" OnClick="btn_ok_Click"></asp:button>
        
</td></tr>
        
</TABLE>  </form>
</body>
</html>

 



posted on 2009-02-17 13:04  天涯之外  阅读(718)  评论(0编辑  收藏  举报