关闭

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

标签: textboxaspstringobjectserverbutton
2283人阅读 评论(0) 收藏 举报
分类:

今天工作不忙,刚好顺便学习一下,把前几天的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>
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:84400次
    • 积分:1349
    • 等级:
    • 排名:千里之外
    • 原创:46篇
    • 转载:9篇
    • 译文:0篇
    • 评论:39条
    最新评论