GridView和DetailView实现增,删,改,查(数据源为后台绑定,非SqlDataSource)

原创 2007年09月25日 16:11:00

今天工作不忙,刚好顺便学习一下,把前几天的gridview的功能增强了一些,顺便也改进了一下。 实现了增,删,该,查,这些基本的功能。有需要的朋友可以看一下。

 后台代码

public partial class GridViewExercise : System.Web.UI.Page
{
    
string ConStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

    
protected void Page_Load(object sender, EventArgs e)
    
{

        SortExprssion();
        SetGridView();
        
if (!IsPostBack)
        
{
            ViewState[
"CompanyName"= "SupplierID";
            ViewState[
"Direction"= "ASC";
            BindGridView();
        }

    }



    
//设置排序表达式
    private void SortExprssion()
    
{
        GridView1.Columns[
3].SortExpression = GridView1.Columns[3].HeaderText.ToString();
    }


    
//设置gridview的属性
    private void SetGridView()
    
{
        GridView1.AllowPaging 
= true;
        GridView1.AllowSorting 
= true;
    }


    
private void  BindGridView()
    
{
        
string QueryCon = "SELECT SupplierID,CompanyName,ContactName,Address,City FROM Suppliers";
        SqlConnection NorthWindCon 
= new SqlConnection(ConStr);
        SqlDataAdapter NorthWindDa 
= new SqlDataAdapter(QueryCon,ConStr);
        DataSet Ds 
= new DataSet();
        NorthWindDa.Fill(Ds, 
"Suppliers");
        GridView1.DataKeyNames 
= new string[] "SupplierID" };
        DataView Dv 
= Ds.Tables["Suppliers"].DefaultView;
        
//排序表达式
        string SortExpress = (string)ViewState["CompanyName"+ " " + (string)ViewState["Direction"];
        Dv.Sort 
= SortExpress;
        
//GridView1.DataSource = Ds.Tables["Suppliers"];
        
//绑定数据源
        GridView1.DataSource = Dv;
        GridView1.DataBind();
    }


    
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    
{

        
if (GridView1.EditIndex != -1)
        
{
            e.Cancel 
= true;
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('编辑模式下禁止换行')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
else
        
{
            DetailsView1.Visible 
= false;
            GridView1.EditIndex 
= e.NewEditIndex;
            BindGridView();
        }

    }



    
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    
{
        GridView1.EditIndex 
= -1;
        BindGridView();
    }



    
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    
{
        
string KeyId = GridView1.DataKeys[e.RowIndex].Value.ToString();
        
string CompanyName = Server.HtmlEncode(((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[1]).Text.ToString());
        
string ContactName = Server.HtmlEncode(((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[1]).Text.ToString());
        
string Address = Server.HtmlEncode(((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[1]).Text.ToString());
        
string City = Server.HtmlEncode(((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[1]).Text.ToString());

        
string UpdateStr = "UPDATE Suppliers SET CompanyName='" + CompanyName + "',ContactName='" + ContactName + "'," +
        
"Address='" + Address + "',City='" + City + " 'WHERE SupplierID='" +KeyId + "";
        SqlConnection UpdateCon 
= new SqlConnection(ConStr);
        SqlCommand UpdateCmd 
= new SqlCommand(UpdateStr,UpdateCon);
        
try
        
{
            UpdateCon.Open();
            UpdateCmd.ExecuteNonQuery();
            GridView1.EditIndex 
= -1;
            BindGridView();
        }

        
catch(Exception ex)
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('更新出错,请重新编辑')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
finally
        
{
            UpdateCon.Dispose();
        }

    }


    
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    
{
        
string KeyId = GridView1.DataKeys[e.RowIndex].Value.ToString();
        
string DeleteStr = "DELETE FROM Suppliers WHERE SupplierID='" + KeyId + "'";
        SqlConnection DeleteCon 
= new SqlConnection(ConStr);
        SqlCommand DeleteCmd 
= new SqlCommand(DeleteStr, DeleteCon);
        
try
        
{
            DeleteCon.Open();
            DeleteCmd.ExecuteNonQuery();
            BindGridView();
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('删除成功')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
catch (Exception ex)
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('删除出错,请检查数据是否有关联')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
finally
        
{
            DeleteCon.Dispose();
        }

    }


    
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    
{
        
if (e.Row.RowType == DataControlRowType.DataRow)
        
{
            
if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            
{
                ((Button)e.Row.Cells[
2].Controls[0]).Attributes["onclick"= "if(!confirm('你真的要删除" + e.Row.Cells[3].Text + "这条记录么?'))return   false;";
            }

        }

    }



    
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    
{
        String SortExpress 
= e.SortExpression;
        
if (ViewState["CompanyName"].ToString() == SortExpress)
        
{
            
if (ViewState["Direction"].ToString() == "DESC")
            
{
                ViewState[
"Direction"= "ASC";
            }

            
else
            
{
                ViewState[
"Direction"= "DESC";
            }

        }

        
else
        
{
            ViewState[
"CompanyName"= e.SortExpression;
        }

        BindGridView();
    }


    
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    
{
        GridView1.PageIndex 
= e.NewPageIndex;
        BindGridView();
    }


    
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    
{
        
//if (GridView1.EditIndex != -1)
        
//{
        
//    GridView1.SelectedIndex = -1;
        
//    e.Cancel = true;
        
//    Literal TxtMsg = new Literal();
        
//    TxtMsg.Text = "<script>alert('编辑模式下禁止选择其他行')</script>";
        
//    Page.Controls.Add(TxtMsg);
        
//}
        
//else
        
//{
        
//    Literal TxtMsg = new Literal();
        
//    TxtMsg.Text = "您选择了第" + (e.NewSelectedIndex + 1) + "行,详细信息如下:<br />";
        
//        for(int i=3;i<GridView1.Columns.Count-1;i++)
        
//        {
        
//            TxtMsg.Text += GridView1.Columns[i].HeaderText + ":" + ((Label)GridView1.Rows[e.NewSelectedIndex].Cells[i].Controls[1]).Text + ",";
        
//        }
        
//    Page.Controls.Add(TxtMsg);
        
//}
        
//绑定detailview并显示
        if (e.NewSelectedIndex >= 0)
        
{
            Session[
"ID"= ((Label)GridView1.Rows[e.NewSelectedIndex].Cells[3].Controls[1]).Text.ToString();
            BindDetailView(Session[
"ID"].ToString());
            DetailsView1.Visible 
= true;

        }

    }


    
private void BindDetailView(string SelectId)
    
{
        
string QueryCon = "SELECT SupplierID,CompanyName,ContactName,Address,City FROM Suppliers WHERE SupplierID='" + SelectId + "";
        SqlConnection DetailCon 
= new SqlConnection(ConStr);
        SqlDataAdapter Da 
= new SqlDataAdapter(QueryCon, DetailCon);
        DataSet DetailDs 
= new DataSet();
        Da.Fill(DetailDs, 
"Suppliers");
        DetailsView1.DataSource 
= DetailDs.Tables["Suppliers"];
        DetailsView1.DataBind();
    }


    
//插入新的一行数据
    protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
    
{
        ((TextBox)DetailsView1.Rows[
0].Cells[1].Controls[0]).ReadOnly = true;
        
//找到detailview中的行中控件的值
        string CompanyName = Server.HtmlEncode(((TextBox)DetailsView1.Rows[1].Cells[1].Controls[0]).Text);
        
string ContactName = Server.HtmlEncode(((TextBox)DetailsView1.Rows[2].Cells[1].Controls[0]).Text);
        
string Address = Server.HtmlEncode(((TextBox)DetailsView1.Rows[3].Cells[1].Controls[0]).Text);
        
string City = Server.HtmlEncode(((TextBox)DetailsView1.Rows[4].Cells[1].Controls[0]).Text);

        
string InsertQuery = "INSERT INTO Suppliers (CompanyName,ContactName,Address,City) VALUES ('" + CompanyName + "','" + ContactName + "','" + Address + "','" + City + "')";
        SqlConnection InsertCon 
= new SqlConnection(ConStr);
        SqlCommand InsertCmd 
= new SqlCommand(InsertQuery,InsertCon);
        
try
        
{
            InsertCon.Open();
            InsertCmd.ExecuteNonQuery();
            BindGridView();
            BindDetailView(Session[
"ID"].ToString());
        }

        
catch (Exception Ex)
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('插入新数据出错,请重新输入')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
finally
        
{
            InsertCon.Dispose();
        }

        
    }


    
//改变detailsview的模式
    protected void DetailsView1_ModeChanging(object sender, DetailsViewModeEventArgs e)
    
{
        
//判断模式
        if (e.NewMode ==DetailsViewMode.Insert)
        
{
            DetailsView1.ChangeMode(DetailsViewMode.Insert);
        }

        
else if (e.NewMode == DetailsViewMode.Edit)
        
{
            DetailsView1.ChangeMode(DetailsViewMode.Edit);
            BindDetailView(Session[
"ID"].ToString());
        }

        
else if (e.CancelingEdit)
        
{
            
//取消插入模式
            if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
            
{
                DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
                BindDetailView(Session[
"ID"].ToString());
            }

            
//取消编辑模式
            else if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
            
{
                DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
                BindDetailView(Session[
"ID"].ToString());
            }

        }

    }


    
protected void DetailsView1_ItemCommand(object sender, DetailsViewCommandEventArgs e)
    
{
        
//判断单击那个按钮
        if (e.CommandName == "Edit")
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('进入编辑模式')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
else if (e.CommandName == "New")
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('插入新的一行')</script>";
            Page.Controls.Add(TxtMsg);
        }


    }


    
protected void DetailsView1_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
    
{
        
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
        
{
            e.Cancel 
= true;
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('插入模式下禁止换行')</script>";
            Page.Controls.Add(TxtMsg);
        }

        
else if (DetailsView1.CurrentMode == DetailsViewMode.Edit)
        
{
            e.Cancel 
= true;
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('编辑模式下禁止换行')</script>";
            Page.Controls.Add(TxtMsg);
        }

    }


    
protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
    
{
        
if (e.Exception != null)
        
{
            
if (e.Exception.GetType() == typeof(System.Data.SqlClient.SqlException))
            
{
                Literal TxtMsg 
= new Literal();
                TxtMsg.Text 
= "<script>alert('删除出错,请检查')</script>";
                Page.Controls.Add(TxtMsg);
                e.ExceptionHandled 
= true;
            }

        }

        
else
        
{
            Literal TxtMsg 
= new Literal();
            TxtMsg.Text 
= "<script>alert('插入数据成功')</script>";
            Page.Controls.Add(TxtMsg);
        }

    }



    
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
    
{
        Literal TxtMsg 
= new Literal();
        TxtMsg.Text 
= "<script>alert('你切换到了" + (GridView1.PageIndex + 1+ "页')</script>";
        Page.Controls.Add(TxtMsg);
    }

 

前台页面代码

 

    <form id="form1" runat="server">
    
<div>
        
<asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#336666"
            BorderStyle
="Double" BorderWidth="3px" CellPadding="4" GridLines="Horizontal" AutoGenerateColumns="False" 
            OnRowCancelingEdit
="GridView1_RowCancelingEdit" 
            OnRowEditing
="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound"
             OnRowDeleting
="GridView1_RowDeleting" OnSorting="GridView1_Sorting" OnPageIndexChanging="GridView1_PageIndexChanging" OnSelectedIndexChanging="GridView1_SelectedIndexChanging" OnPageIndexChanged="GridView1_PageIndexChanged">
            
<FooterStyle BackColor="White" ForeColor="#333333" />
            
<RowStyle BackColor="White" ForeColor="#333333" />
            
<SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
            
<Columns>
                
<asp:CommandField ButtonType="Button" ShowSelectButton="True" />
                
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
                
<asp:CommandField ButtonType="Button" ShowDeleteButton="True" />
                
<asp:TemplateField HeaderText="SupplierID">
                    
<EditItemTemplate>
                        
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("SupplierID") %>' ReadOnly="True"></asp:TextBox>
                    
</EditItemTemplate>
                    
<ItemTemplate>
                        
<asp:Label ID="Label1" runat="server" Text='<%# Bind("SupplierID") %>'></asp:Label>
                    
</ItemTemplate>
                
</asp:TemplateField>
                
<asp:TemplateField HeaderText="CompanyName">
                    
<EditItemTemplate>
                        
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("CompanyName") %>'></asp:TextBox><asp:RequiredFieldValidator
                            
ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox2" ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>
                    
</EditItemTemplate>
                    
<ItemTemplate>
                        
<asp:Label ID="Label2" runat="server" Text='<%# Bind("CompanyName") %>'></asp:Label>
                    
</ItemTemplate>
                
</asp:TemplateField>
                
<asp:TemplateField HeaderText="ContactName">
                    
<EditItemTemplate>
                        
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("ContactName") %>'></asp:TextBox>
                    
</EditItemTemplate>
                    
<ItemTemplate>
                        
<asp:Label ID="Label3" runat="server" Text='<%# Bind("ContactName") %>'></asp:Label>
                    
</ItemTemplate>
                
</asp:TemplateField>
                
<asp:TemplateField HeaderText="Address">
                    
<EditItemTemplate>
                        
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Address") %>'></asp:TextBox>
                    
</EditItemTemplate>
                    
<ItemTemplate>
                        
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Address") %>'></asp:Label>
                    
</ItemTemplate>
                
</asp:TemplateField>
                
<asp:TemplateField HeaderText="City">
                    
<EditItemTemplate>
                        
<asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
                    
</EditItemTemplate>
                    
<ItemTemplate>
                        
<asp:Label ID="Label5" runat="server" Text='<%# Bind("City") %>'></asp:Label>
                    
</ItemTemplate>
                
</asp:TemplateField>
            
</Columns>
        
</asp:GridView>
        
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" BackColor="White"
            BorderColor
="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
            GridLines
="Horizontal" Height="50px" OnItemCommand="DetailsView1_ItemCommand"
            OnItemInserting
="DetailsView1_ItemInserting" OnModeChanging="DetailsView1_ModeChanging"
            OnPageIndexChanging
="DetailsView1_PageIndexChanging" Visible="False" Width="125px" OnItemInserted="DetailsView1_ItemInserted">
            
<FooterStyle BackColor="White" ForeColor="#333333" />
            
<EditRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            
<RowStyle BackColor="White" ForeColor="#333333" />
            
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            
<Fields>
                
<asp:BoundField DataField="SupplierID" HeaderText="SupplierID" ReadOnly="True" />
                
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
                
<asp:BoundField DataField="ContactName" HeaderText="ContactName" />
                
<asp:BoundField DataField="Address" HeaderText="Address" />
                
<asp:BoundField DataField="City" HeaderText="City" />
                
<asp:CommandField ButtonType="Button" ShowInsertButton="True" />
                
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
                
<asp:CommandField ButtonType="Button" ShowDeleteButton="True" />
            
</Fields>
            
<HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
        
</asp:DetailsView>
    
    
</div>
    
</form>
 
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

控件(五)——Gridview控件以SqlDataSource控件为数据源实现换肤功能

皮肤是应用到一个控件上的样式信息,这些内容保存在.skin文件中。然后控件在使用皮肤时,设置它的skinID属性。如果不设置,它会自动设置为默认值。 主题实际上是皮肤的集合,保存在Thremes子目录...

gridview 实现排序 (在不是使用sqlDataSource控件,而在后台编码绑定gridview时,指定那个字段排序时使用。本例用了单层结构,可修改后应用于多层)

GridView控件提供了用于实现排序功能的接口,通过设置相关属性并实现排序事件的处理程序就可以完成排序功能。我们将在【例8-4】提供的界面的基础上实现排序功能。 【例8-5】演示为GridView...

控件(七)——GridView控件以SqlDataSource控件为数据源显示数据

GridView控件与SqlDataSource控件就不做详细介绍了,大家都比较熟悉,而且也比较好理解。 下面直接进入例子: 本例子中首先拖一个GridView控件GridView1,配置一下它的数据...

wpf绑定用户控件及listview(gridview)数据源

用户控件: 前台界面 <UserControl x:Class="testUserControl.project" xmlns="http://schemas.micr...

flex datagrid 嵌checkbox实现全选与数据存储(非绑定数据源)

重写了DataGrid,主要是为了得到DataGrid的listItems属性,listItems保存了当前现显示的每一行的信息,还用了个ArrayCollection保存被选中了行的信息。 MyD...

C#后台生成gridview列,同时绑定多个表数据

通常在开发中会遇到一个界面需要读取多个表的数据单独显示到界面当中,一般可能会想用多个gridview来实现数据的读取,但是期间会导致代码冗余量增加,因而会想用一个空间去实现对此利用。 前台index...

除非指定UpdateCommand,否则数据源SqlDataSource不支持更新操作

今天在做东西,更新数据库,数据库更新成功了,可是sqldatasource却求支持,于是我找了所有可能的原因,最后终于解决了。就是更新完数据库一定要记得更新sqldatasource!虽然不是什么大错...

树控件绑定数据源.rar

  • 2010-07-01 12:24
  • 40KB
  • 下载

绑定数据源到ListView.rar

  • 2010-07-01 11:32
  • 41KB
  • 下载

控件(三)——TreeView控件以XmlDataSource控件为数据源实现简单的绑定

TreeView控件功能非常强大,今天,我们只是窥其一角。 我们实现的例子是:TreeView控件与XmlDataSource控件绑定,然后在网页显示选中项。 首先我们添加一个xml,取名为tv.xm...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)