C#.net使用Gridview1嵌套Gridview2,在Gridview2中使用Dropdownlist问题?

来源:互联网 发布:清华大学图书馆数据库 编辑:程序博客网 时间:2024/06/03 18:14

前台代码:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>Editable Nested Grid View</title>
    <script language=javascript type="text/javascript">
    function expandcollapse(obj,row)
    {
        var div = document.getElementById(obj);
        var img = document.getElementById('img' + obj);
       
        if (div.style.display == "none")
        {
            div.style.display = "block";
            if (row == 'alt')
            {
                img.src = "minus.gif";
            }
            else
            {
                img.src = "minus.gif";
            }
            img.alt = "Close to view other Customers";
        }
        else
        {
            div.style.display = "none";
            if (row == 'alt')
            {
                img.src = "plus.gif";
            }
            else
            {
                img.src = "plus.gif";
            }
            img.alt = "Expand to show Orders";
        }
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" AllowPaging="True" BackColor="#f1f1f1"
            AutoGenerateColumns=false DataSourceID="AccessDataSource1" DataKeyNames="bocnclass"
            style="Z-INDEX: 101; LEFT: 8px; POSITION: absolute; TOP: 32px" ShowFooter=true Font-Size=Small
            Font-Names="Verdana" runat="server" GridLines=None OnRowDataBound="GridView1_RowDataBound"
            OnRowCommand = "GridView1_RowCommand" OnRowUpdating = "GridView1_RowUpdating" BorderStyle=Outset
            OnRowDeleting = "GridView1_RowDeleting" OnRowDeleted = "GridView1_RowDeleted"
            OnRowUpdated = "GridView1_RowUpdated" AllowSorting=true>
            <RowStyle BackColor="Gainsboro" />
            <AlternatingRowStyle BackColor="White" />
            <HeaderStyle BackColor="#0083C1" ForeColor="White"/>
            <FooterStyle BackColor="White" />
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <a href="javascript:expandcollapse('div<%# Eval("bocnclass") %>', 'one');">
                            <img id="imgdiv<%# Eval("bocnclass") %>" alt="Click to show/hide Orders for Customer <%# Eval("bocnclass") %>"  width="9px" border="0" src="plus.gif"/>
                        </a>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="科目类别" SortExpression="bocnclass">
                    <ItemTemplate>
                                        <%# Eval("bocnclass")%>
                                    </ItemTemplate>
                                    <EditItemTemplate>
                                        <asp:HiddenField ID="bocnclass" runat="server" Value='<%# Eval("bocnclass") %>' />
                                        <asp:DropDownList ID="txtbocnclass" runat="server" Width="90px" />
                                    </EditItemTemplate>
                                    <FooterTemplate>
                                    <asp:HiddenField ID="bocnclass" runat="server" Value='<%# Eval("bocnclass") %>' />
                                    <asp:DropDownList ID="txtbocnclass" runat="server" Width="90px"/>
                                    </FooterTemplate>
                                    <ItemStyle Width="100px" />
                                </asp:TemplateField>
                <asp:TemplateField HeaderText="部门" SortExpression="bodept">
                    <ItemTemplate><%# Eval("bodept") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="bodept" Text='<%# Eval("bodept") %>' runat="server"></asp:Label>
                    </EditItemTemplate>
                                    <FooterTemplate>
                                    <asp:HiddenField ID="bodept" runat="server" Value='<%# Eval("bodept") %>' />
                                    <asp:DropDownList ID="txtbodept" runat="server" Width="90px"  AutoPostBack="true"  OnTextChanged="DropSelectedIndexChanged"/>
                                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Contact Name" SortExpression="boname">
                    <ItemTemplate><%# Eval("boname") %></ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="boname" Text='<%# Eval("boname") %>' runat="server"></asp:Label>
                    </EditItemTemplate>
                                    <FooterTemplate>
                                    <asp:HiddenField ID="boname" runat="server" Value='<%# Eval("boname") %>' />
                                    <asp:DropDownList ID="txtboname" runat="server" Width="90px" />
                                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Contact Title" SortExpression="bophase">
                    <ItemTemplate><%# Eval("bophase")%></ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="txtbophase" Text='<%# Eval("bophase") %>' runat="server"></asp:Label>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:Label ID="txtbophase" Text='' runat="server"></asp:Label>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="bointerval" SortExpression="bointerval">
                    <ItemTemplate><%# Eval("bointerval")%></ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="txtbointerval" Text='<%# Eval("bointerval") %>' runat="server"></asp:Label>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:Label ID="txtbointerval" Text='' runat="server"></asp:Label>
                    </FooterTemplate>
                </asp:TemplateField>
               
      
       <asp:CommandField HeaderText="Edit" ShowEditButton="True" />
       <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:LinkButton ID="linkDeleteCust" CommandName="Delete" runat="server">Delete</asp:LinkButton>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:LinkButton ID="linkAddCust" CommandName="AddCustomer" runat="server">Add</asp:LinkButton>
                    </FooterTemplate>
                </asp:TemplateField>
      
       <asp:TemplateField>
           <ItemTemplate>
               <tr>
                            <td colspan="100%">
                                <div id="div<%# Eval("bocnclass") %>" style="display:none;position:relative;left:15px;OVERFLOW: auto;WIDTH:97%" >
                                    <asp:GridView ID="GridView2" AllowPaging="True" AllowSorting="true" BackColor="White" Width=100% Font-Size=X-Small
                                        AutoGenerateColumns=false Font-Names="Verdana" runat="server" DataKeyNames="bocnclass" ShowFooter=true
                                        OnPageIndexChanging="GridView2_PageIndexChanging" OnRowUpdating = "GridView2_RowUpdating"
                                        OnRowCommand = "GridView2_RowCommand" OnRowEditing = "GridView2_RowEditing" GridLines=None
                                        OnRowUpdated = "GridView2_RowUpdated" OnRowCancelingEdit = "GridView2_CancelingEdit" OnRowDataBound = "GridView2_RowDataBound"
                                        OnRowDeleting = "GridView2_RowDeleting" OnRowDeleted = "GridView2_RowDeleted" OnSorting = "GridView2_Sorting"
                                        BorderStyle=Double BorderColor="#0083C1">
                                        <RowStyle BackColor="Gainsboro" />
                                        <AlternatingRowStyle BackColor="White" />
                                        <HeaderStyle BackColor="#0083C1" ForeColor="White"/>
                                        <FooterStyle BackColor="White" />
                                        <Columns>
                                            <asp:TemplateField HeaderText="bodstitle" SortExpression="bodstitle">
                                                <ItemTemplate>
                                                    <asp:Label ID="lblbodstitle" Text='<%# Eval("bodstitle") %>' runat="server"></asp:Label>
                                                </ItemTemplate>
                                                <EditItemTemplate>
                                                    <asp:HiddenField ID="bodstitle" runat="server" Value='<%# Eval("bodstitle") %>' />
                                                    <asp:DropDownList ID="txtbodstitle" runat="server" Width="90px" />
                                                </EditItemTemplate>
                                    <FooterTemplate>
                                    <asp:HiddenField ID="bodstitle" runat="server" Value='<%# Eval("bodstitle") %>' />
                                    <asp:DropDownList ID="txtbodstitle" runat="server" Width="90px" />
                                    </FooterTemplate>                                           
                                    </asp:TemplateField>
                                           
                                            <asp:TemplateField HeaderText="bodphase" SortExpression="bodphase">
                                                <ItemTemplate><%# Eval("bodphase")%></ItemTemplate>
                                                <EditItemTemplate>
                                                    <asp:TextBox ID="txtbodphase" Text='<%# Eval("bodphase")%>' runat="server"></asp:TextBox>
                                                </EditItemTemplate>
                                                <FooterTemplate>
                                                    <asp:TextBox ID="txtbodphase" Text='' runat="server"></asp:TextBox>
                                                </FooterTemplate>
                                            </asp:TemplateField>
                                              <asp:TemplateField HeaderText="bodjan" SortExpression="bodjan">
                                                <ItemTemplate><%# Eval("bodjan")%></ItemTemplate>
                                                <EditItemTemplate>
                                                    <asp:TextBox ID="txtShipAdress" Text='<%# Eval("bodjan")%>' runat="server"></asp:TextBox>
                                                </EditItemTemplate>
                                                <FooterTemplate>
                                                    <asp:TextBox ID="txtShipAdress" Text='' runat="server"></asp:TextBox>
                                                </FooterTemplate>
                                            </asp:TemplateField>
                                            <asp:TemplateField HeaderText="bodfeb" SortExpression="bodfeb">
                                                <ItemTemplate><%# Eval("bodfeb")%></ItemTemplate>
                                                <EditItemTemplate>
                                                    <asp:TextBox ID="bodfeb" Text='<%# Eval("bodfeb")%>' runat="server"></asp:TextBox>
                                                </EditItemTemplate>
                                                <FooterTemplate>
                                                    <asp:TextBox ID="txtbodfeb" Text='' runat="server"></asp:TextBox>
                                                </FooterTemplate>
                                            </asp:TemplateField>

                                           
                                   <asp:CommandField HeaderText="Edit" ShowEditButton="True" />
                                   <asp:TemplateField HeaderText="Delete">
                                                 <ItemTemplate>
                                                    <asp:LinkButton ID="linkDeleteCust" CommandName="Delete" runat="server">Delete</asp:LinkButton>
                                                 </ItemTemplate>
                                                 <FooterTemplate>
                                                    <asp:LinkButton ID="linkAddOrder" CommandName="AddOrder" runat="server">Add</asp:LinkButton>
                                                 </FooterTemplate>
                                            </asp:TemplateField>
                                        </Columns>
                                   </asp:GridView>
                                </div>
                             </td>
                        </tr>
           </ItemTemplate>         
       </asp:TemplateField>      
   </Columns>
        </asp:GridView>
            <asp:SqlDataSource ID="AccessDataSource1" runat="server"
            ConnectionString="Data Source=E100313D;Initial Catalog=Dinfo;Persist Security Info=True;User ID=sa;Password=tac26901333"
           
            SelectCommand="SELECT  bodept,boname,bophase,bosdate+'~'+ boedate AS bointerval,bocnclass FROM Dinfo_BudgetOverall   ORDER BY bocnclass"></asp:SqlDataSource>       
    </div>
              
    </form>
</body>
</html>
后台代码:

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Common;

public partial class _Default : System.Web.UI.Page
{

    #region Variables
    string gvUniqueID = String.Empty;
    int gvNewPageIndex = 0;
    int gvEditIndex = -1;
    string gvSortExpr = String.Empty;

   
    private string gvSortDir
    {

        get { return ViewState["SortDirection"] as string ?? "ASC"; }

        set { ViewState["SortDirection"] = value; }

    }
    #endregion

    //This procedure returns the Sort Direction
    private string GetSortDirection()
    {
        switch (gvSortDir)
        {
            case "ASC":
                gvSortDir = "DESC";
                break;

            case "DESC":
                gvSortDir = "ASC";
                break;
        }
        return gvSortDir;
    }

    //This procedure prepares the query to bind the child GridView
    private SqlDataSource ChildDataSource(string strCustometId, string strSort)
    {

        string strQRY = "";
        SqlDataSource dsTemp = new SqlDataSource();
        dsTemp.ConnectionString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Dinfo;uid=sa;pwd=tac26901333";
        strQRY = "SELECT [Dinfo_BudgetOverallDetail].[bocnclass],[Dinfo_BudgetOverallDetail].[bodstitle]," +
                                "[Dinfo_BudgetOverallDetail].[bodphase],[Dinfo_BudgetOverallDetail].[bodjan],[Dinfo_BudgetOverallDetail].[bodfeb] FROM [Dinfo_BudgetOverallDetail]" +
                                " WHERE [Dinfo_BudgetOverallDetail].[bocnclass] = '" + strCustometId + "'" +
                                "UNION ALL " +
                                "SELECT '" + strCustometId + "','','','','' FROM [Dinfo_BudgetOverallDetail] WHERE [Dinfo_BudgetOverallDetail].[bocnclass] = '" + strCustometId + "'" +
                                "HAVING COUNT(*)=0 " + strSort;

        dsTemp.SelectCommand = strQRY;
        return dsTemp;

 

 

    }
          
 
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    #region GridView1 Event Handlers
    //This event occurs for each row
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //为DropDownList预算类别绑定值
        if (((DropDownList)e.Row.FindControl("txtbocnclass")) != null)
        {
            DropDownList txtbocnclass = (DropDownList)e.Row.FindControl("txtbocnclass");
            txtbocnclass.Items.Clear();
            //科目类别list修改更新使用
            SqlConnection modelsc = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DinfoConnectionString"].ToString());
            string modelsql = "SELECT DISTINCT bmcntitle FROM Dinfo_BudgetMainject ORDER BY bmcntitle DESC";
            SqlDataAdapter msda = new SqlDataAdapter(modelsql, modelsc);
            modelsc.Open();
            DataSet modeldt = new DataSet();
            msda.Fill(modeldt, "MyTable");

            txtbocnclass.AppendDataBoundItems = true;
            txtbocnclass.Items.Add(new ListItem("---请选择---", "0"));
            txtbocnclass.DataSource = modeldt.Tables["MyTable"].DefaultView;
            txtbocnclass.DataTextField = "bmcntitle";
            //DropDownList1.DataValueField = "MC001";
            txtbocnclass.DataBind();
            modelsc.Close();

            //  选中 DropDownList
            txtbocnclass.SelectedValue = ((HiddenField)e.Row.FindControl("bocnclass")).Value;

        }
        //为DropDownList部门绑定值
        if (((DropDownList)e.Row.FindControl("txtbodept")) != null)
        {
            DropDownList txtbodept = (DropDownList)e.Row.FindControl("txtbodept");
            txtbodept.Items.Clear();
            //科目类别list修改更新使用
            SqlConnection modelsc = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DinfoConnectionString"].ToString());
            string modelsql = "SELECT DISTINCT Name FROM Dinfo_UnitName ORDER BY Name DESC";
            SqlDataAdapter msda = new SqlDataAdapter(modelsql, modelsc);
            modelsc.Open();
            DataSet modeldt = new DataSet();
            msda.Fill(modeldt, "MyTable");

            txtbodept.AppendDataBoundItems = true;
            txtbodept.Items.Add(new ListItem("---请选择---", "0"));
            txtbodept.DataSource = modeldt.Tables["MyTable"].DefaultView;
            txtbodept.DataTextField = "Name";
            //DropDownList1.DataValueField = "MC001";
            txtbodept.DataBind();
            modelsc.Close();

            //  选中 DropDownList
            txtbodept.SelectedValue = ((HiddenField)e.Row.FindControl("bodept")).Value;

        }


        GridViewRow row = e.Row;
        string strSort = string.Empty;

        // Make sure we aren't in header/footer rows
        if (row.DataItem == null)
        {
            return;
        }

        //Find Child GridView control
        GridView gv = new GridView();
        gv = (GridView)row.FindControl("GridView2");

        //Check if any additional conditions (Paging, Sorting, Editing, etc) to be applied on child GridView
        if (gv.UniqueID == gvUniqueID)
        {
            gv.PageIndex = gvNewPageIndex;
            gv.EditIndex = gvEditIndex;
            //Check if Sorting used
            if (gvSortExpr != string.Empty)
            {
                GetSortDirection();
                strSort = " ORDER BY " + string.Format("{0} {1}", gvSortExpr, gvSortDir);
            }
            //Expand the Child grid
            ClientScript.RegisterStartupScript(GetType(), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + ((DataRowView)e.Row.DataItem)["bocnclass"].ToString() + "','one');</script>");
        }

        //Prepare the query for Child GridView by passing the Customer ID of the parent row
      
        gv.DataSource = ChildDataSource(((DataRowView)e.Row.DataItem)["bocnclass"].ToString(), strSort);
        gv.DataBind();

 

 


        //Add delete confirmation message for Customer
        LinkButton l = (LinkButton)e.Row.FindControl("linkDeleteCust");
        l.Attributes.Add("onclick", "javascript:return " +
        "confirm('Are you sure you want to delete this Customer " +
        DataBinder.Eval(e.Row.DataItem, "bocnclass") + "')");

    }

    //This event occurs for any operation on the row of the grid
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {


        //Check if Add button clicked
        if (e.CommandName == "AddCustomer")
        {
            try
            {
                //Get the values stored in the text boxes
                string strbodept = ((TextBox)GridView1.FooterRow.FindControl("txtbodept")).Text;
                string strboname = ((TextBox)GridView1.FooterRow.FindControl("txtboname")).Text;
                string strbophase = ((TextBox)GridView1.FooterRow.FindControl("txtbophase")).Text;
                string strbointerval = ((TextBox)GridView1.FooterRow.FindControl("txtbointerval")).Text;
                string strbocnclass = ((TextBox)GridView1.FooterRow.FindControl("txtbocnclass")).Text;

                //Prepare the Insert Command of the DataSource control
                string strSQL = "";
                strSQL = "INSERT INTO Customers (bocnclass, bodept, boname, " +
                        "bophase, bointerval) VALUES ('" + strbocnclass + "','" + strbodept + "','" +
                        strboname + "','" + strbophase + "','" + strbointerval + "')";

                AccessDataSource1.InsertCommand = strSQL;
                AccessDataSource1.Insert();
                ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Customer added successfully');</script>");

                //Re bind the grid to refresh the data
                GridView1.DataBind();
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + ex.Message.ToString().Replace("'", "") + "');</script>");
            }
        }
    }
    //protected void CnSelectedIndexChanged(object sender, EventArgs e)
    //{


    //    //为DropDownList预算科目绑定值


    //}
    protected void DropSelectedIndexChanged(object sender, EventArgs e)
    {
        string strCompanyName = ((DropDownList)GridView1.FooterRow.FindControl("txtbodept")).SelectedValue;
        //为DropDownList人员绑定值
        if (((DropDownList)GridView1.FooterRow.FindControl("txtboname")) != null)
        {
            DropDownList txtboname = ((DropDownList)GridView1.FooterRow.FindControl("txtboname"));
            txtboname.Items.Clear();
            //科目类别list修改更新使用
            SqlConnection bonamesc = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DinfoConnectionString"].ToString());
            string bonamesql = "SELECT DISTINCT Realname FROM Dinfo_username  WHERE Unit='" + strCompanyName + "'ORDER BY Realname DESC";
            SqlDataAdapter bonamesda = new SqlDataAdapter(bonamesql, bonamesc);
            bonamesc.Open();
            DataSet bonamedt = new DataSet();
            bonamesda.Fill(bonamedt, "MyTable");

            txtboname.AppendDataBoundItems = true;
            txtboname.Items.Add(new ListItem("---请选择---", "0"));
            txtboname.DataSource = bonamedt.Tables["MyTable"].DefaultView;
            txtboname.DataTextField = "Realname";
            //DropDownList1.DataValueField = "MC001";
            txtboname.DataBind();
            bonamesc.Close();

            //  选中 DropDownList
            //txtbocnclass.SelectedValue = ((HiddenField)e.Row.FindControl("bocnclass")).Value;


        }
       
    }
    //This event occurs on click of the Update button
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //Get the values stored in the text boxes
        string strbodept = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtbodept")).Text;
        string strboname = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtboname")).Text;
        string strbophase = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtbophase")).Text;
        string strbointerval = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtbointerval")).Text;
        string strbocnclass = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblbocnclass")).Text;

        try
        {
            //Prepare the Update Command of the DataSource control
            string strSQL = "";
            strSQL = "UPDATE Customers set bodept = '" + strbodept + "'" +
                     ",boname = '" + strboname + "'" +
                     ",bophase = '" + strbophase + "'" +
                     ",bointerval = '" + strbointerval + "'" +
                     " WHERE bocnclass = '" + strbocnclass + "'";
            AccessDataSource1.UpdateCommand = strSQL;
            AccessDataSource1.Update();
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Customer updated successfully');</script>");
        }
        catch { }
    }

    //This event occurs after RowUpdating to catch any constraints while updating
    protected void GridView1_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        //Check if there is any exception while deleting
        if (e.Exception != null)
        {
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
            e.ExceptionHandled = true;
        }
    }

    //This event occurs on click of the Delete button
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //Get the value       
        string strbocnclass = ((Label)GridView1.Rows[e.RowIndex].FindControl("lblbocnclass")).Text;

        //Prepare the delete Command of the DataSource control
        string strSQL = "";

        try
        {
            strSQL = "DELETE from Customers WHERE bocnclass = '" + strbocnclass + "'";
            AccessDataSource1.DeleteCommand = strSQL;
            AccessDataSource1.Delete();
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Customer deleted successfully');</script>");
        }
        catch { }
    }

    //This event occurs after RowDeleting to catch any constraints while deleting
    protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        //Check if there is any exception while deleting
        if (e.Exception != null)
        {
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
            e.ExceptionHandled = true;
        }
    }
    #endregion

    #region GridView2 Event Handlers
    protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView gvTemp = (GridView)sender;
        gvUniqueID = gvTemp.UniqueID;
        gvNewPageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }

    protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "AddOrder")
        {
            try
            {
                GridView gvTemp = (GridView)sender;
                gvUniqueID = gvTemp.UniqueID;

                //Get the values stored in the text boxes
                string strbocnclass = gvTemp.DataKeys[0].Value.ToString();  //Customer ID is stored as DataKeyNames
                string strbodphase = ((TextBox)gvTemp.FooterRow.FindControl("txtbodphase")).Text;
                string strShipperName = ((TextBox)gvTemp.FooterRow.FindControl("txtShipperName")).Text;
                string strShipAdress = ((TextBox)gvTemp.FooterRow.FindControl("txtShipAdress")).Text;

                //Prepare the Insert Command of the DataSource control
                string strSQL = "";
                strSQL = "INSERT INTO Orders (bocnclass, bodphase, bodinterval, " +
                        "bodjan) VALUES ('" + strbocnclass + "'," + float.Parse(strbodphase) + ",'" +
                        strShipperName + "','" + strShipAdress + "')";

                AccessDataSource1.InsertCommand = strSQL;
                AccessDataSource1.Insert();
                ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order added successfully');</script>");

                GridView1.DataBind();
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + ex.Message.ToString().Replace("'", "") + "');</script>");
            }
        }
    }

    protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView gvTemp = (GridView)sender;
        gvUniqueID = gvTemp.UniqueID;
        gvEditIndex = e.NewEditIndex;
        GridView1.DataBind();
    }

    protected void GridView2_CancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView gvTemp = (GridView)sender;
        gvUniqueID = gvTemp.UniqueID;
        gvEditIndex = -1;
        GridView1.DataBind();
    }

    protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            GridView gvTemp = (GridView)sender;
            gvUniqueID = gvTemp.UniqueID;

            //Get the values stored in the text boxes
            string strbodstitle = ((Label)gvTemp.Rows[e.RowIndex].FindControl("lblbodstitle")).Text;
            string strbodphase = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtbodphase")).Text;
            string strShipperName = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtShipperName")).Text;
            string strShipAdress = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtShipAdress")).Text;

            //Prepare the Update Command of the DataSource control
            AccessDataSource dsTemp = new AccessDataSource();
            dsTemp.DataFile = "App_Data/Northwind.mdb";
            string strSQL = "";
            strSQL = "UPDATE Orders set bodphase = " + float.Parse(strbodphase) + "" +
                     ",bodinterval = '" + strShipperName + "'" +
                     ",bodjan = '" + strShipAdress + "'" +
                     " WHERE bodstitle = " + strbodstitle;
            dsTemp.UpdateCommand = strSQL;
            dsTemp.Update();
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order updated successfully');</script>");

            //Reset Edit Index
            gvEditIndex = -1;

            GridView1.DataBind();
        }
        catch { }
    }

    protected void GridView2_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {
        //Check if there is any exception while deleting
        if (e.Exception != null)
        {
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
            e.ExceptionHandled = true;
        }
    }

    protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView gvTemp = (GridView)sender;
        gvUniqueID = gvTemp.UniqueID;

        //Get the value       
        string strbodstitle = ((Label)gvTemp.Rows[e.RowIndex].FindControl("lblbodstitle")).Text;

        //Prepare the Update Command of the DataSource control
        string strSQL = "";

        try
        {
            strSQL = "DELETE from Orders WHERE bodstitle = " + strbodstitle;
            AccessDataSource dsTemp = new AccessDataSource();
            dsTemp.DataFile = "App_Data/Northwind.mdb";
            dsTemp.DeleteCommand = strSQL;
            dsTemp.Delete();
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('Order deleted successfully');</script>");
            GridView1.DataBind();
        }
        catch { }
    }

    protected void GridView2_RowDeleted(object sender, GridViewDeletedEventArgs e)
    {
        //Check if there is any exception while deleting
        if (e.Exception != null)
        {
            ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('" + e.Exception.Message.ToString().Replace("'", "") + "');</script>");
            e.ExceptionHandled = true;
        }
    }

    protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (((DropDownList)e.Row.FindControl("txtbocnclass")) == null)
        {
            GridView Grd = e.Row.Cells[0].FindControl("GridView2") as GridView;

            DropDownList txtbodstitle = (DropDownList)Grd.FooterRow.FindControl("txtbodstitle");
            txtbodstitle.Items.Clear();
            //科目类别list修改更新使用
            SqlConnection bonamesc = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DinfoConnectionString"].ToString());
            string bonamesql = "SELECT DISTINCT Realname FROM Dinfo_username  WHERE Unit='" + ((DataRowView)GridView1.FooterRow.DataItem)["bocnclass"].ToString() + "'ORDER BY Realname DESC";
            SqlDataAdapter bonamesda = new SqlDataAdapter(bonamesql, bonamesc);
            bonamesc.Open();
            DataSet bonamedt = new DataSet();
            bonamesda.Fill(bonamedt, "MyTable");

            txtbodstitle.AppendDataBoundItems = true;
            txtbodstitle.Items.Add(new ListItem("---请选择---", "0"));
            txtbodstitle.DataSource = bonamedt.Tables["MyTable"].DefaultView;
            txtbodstitle.DataTextField = "Realname";
            //DropDownList1.DataValueField = "MC001";
            txtbodstitle.DataBind();
            bonamesc.Close();
        }

        //Check if this is our Blank Row being databound, if so make the row invisible
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (((DataRowView)e.Row.DataItem)["bodstitle"].ToString() == String.Empty) e.Row.Visible = false;
        }


    }

    protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
    {
        GridView gvTemp = (GridView)sender;
        gvUniqueID = gvTemp.UniqueID;
        gvSortExpr = e.SortExpression;       
        GridView1.DataBind();
    }
    #endregion
   
}

每次执行色代码中提示:未将对象引用设置到对象的实例。请高手帮忙!