Visual Studio 12 - 在提交时插入页脚行的Gridview

时间:2014-06-10 20:00:39

标签: c# asp.net visual-studio-2012 gridview

我有一个gridview,当用户点击提交时,我需要在文本框中插入带有数据的页脚行。我一遍又一遍地试过,我无法解决以下错误:

对象引用未设置为对象的实例。错误在后面的代码中的Textbox AddName代码行中标记。

这是我的代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs"    Inherits="WorkOrder.Admin" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="Style.css" rel="stylesheet" type="text/css" />
<link href="msgBoxLight.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.8.0.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.msgBox.js" type="text/javascript"></script>
</head>
<body>
<form id="form2" runat="server">
<div>
    <asp:Panel ID="Panel1" runat="server" Width="1020px">
        <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/mast_left.png" />          
    </asp:Panel>       
    </div>

    <div class="Section"> <hr /><h2>
        Online Work Order Form - (Admin)</h2>
    </div>
    <br />
    <asp:Label ID="Label2" runat="server" Text="Select data you want to view and click the submit button:" CssClass="label"></asp:Label><br /><br />

<div>
    <asp:GridView ID="GridViewAdmin" runat="server" AutoGenerateColumns="False" AutoGenerateEditButton="True" DataSourceID="SqlDataSource1" DataKeyNames="WO_ID" EnableModelValidation="True"
         >
        <Columns>



            <asp:BoundField DataField="WO_ID" HeaderText="WO_ID"  ReadOnly="True" SortExpression="WO_ID" />
            <asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" />
            <asp:BoundField DataField="Job_Title" HeaderText="Job_Title" ReadOnly="True" SortExpression="Job_Title" />
            <asp:BoundField DataField="Job_Assigned_To" HeaderText="Job_Assigned_To" SortExpression="Job_Assigned_To" />
            <asp:CheckBoxField DataField="Completed" HeaderText="Completed" SortExpression="Completed" />
            <asp:BoundField DataField="Completed_Date" HeaderText="Completed_Date" SortExpression="Completed_Date" />
            <asp:BoundField DataField="Notes" HeaderText="Notes" SortExpression="Notes" />

        </Columns>
    </asp:GridView>


    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>" 
        SelectCommand="SELECT [WO_ID], [Name], [Job_Type], [Job_UpdateName], [Job_Title], [Job_Description], [Job_Assigned_To], [Completed], [Completed_Date], [Notes] FROM [WO_Submission_Details]"
        UpdateCommand="UPDATE [WO_Submission_Details] SET [Job_Assigned_To] = @Job_Assigned_To, [Completed] = @Completed, [Completed_Date] = @Completed_Date, [Notes] = @Notes WHERE [WO_ID] = @WO_ID">
    </asp:SqlDataSource>
</div>
    <br /> <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/AdminReport.aspx">Work Order Report</asp:HyperLink>
    <br />
    <br />
<hr />


    <br />
    <asp:Label ID="Label1" runat="server" Text="Enter name below to add to Marketing employee table" CssClass="label"></asp:Label>
     <br />
    <br />
    <asp:Label ID="Label3" runat="server" Text="Name:" CssClass="label"></asp:Label>&nbsp;

<asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox><br /><br />

     <asp:Label ID="Label4" runat="server" Text="Email:" CssClass="label"></asp:Label>&nbsp;

<asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
    <br /><br />
      &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
     <br /><br />
    <asp:GridView ID="GridViewStaff" runat="server"
         AutoGenerateColumns="False" 
         AutoGenerateDeleteButton="True" 
        BackColor="White" BorderColor="#3366CC" 
        BorderStyle="None" BorderWidth="1px" CellPadding="5" 
         DataSourceID="SqlDataSource2"  datakeynames="ID" AllowSorting="True">
        <Columns>

            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label runat="server" Text='<%#Eval("Name") %>' />
                </ItemTemplate>
               <FooterTemplate>
                    <asp:TextBox ID="txtAddName" runat="server" Width="170px"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
             <ItemTemplate>
                    <asp:Label runat="server" text='<%#Eval("Email")%>'/>
            </ItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtAddEmail" runat="server" Width="170px"></asp:TextBox>
                </FooterTemplate>
            </asp:TemplateField>

        </Columns>
         <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
        <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
        <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
        <RowStyle BackColor="White" ForeColor="#003399" />
        <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
    </asp:GridView>
 <asp:SqlDataSource ID="SqlDataSource2" runat="server"
    ConnectionString="<%$ ConnectionStrings:ZSC_WorkOrdersConnectionString %>" 
    SelectCommand="SELECT * FROM [Marketing_Staff]" InsertCommand="INSERT INTO [Marketing_Staff] ([Name], [Email]) VALUES (@Name, @Email)">

    <InsertParameters>

<asp:Parameter Type="String" Name="Name"></asp:Parameter>
<asp:Parameter Type="String" Name="Email"></asp:Parameter>


</InsertParameters>
    </asp:SqlDataSource>     

     </form>
</body>

</html>

代码背后:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Design;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Text;
using System.IO;


    namespace WorkOrder
    {

    public partial class Admin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            bindgridView();
        }


        protected void btnSubmit_Click(object sender, EventArgs e)
        {


            TextBox AddName = GridViewStaff.FooterRow.FindControl("txtAddName") as TextBox;

            // Response.Write(AddName.Text);
            //TextBox Email = GridViewStaff.FooterRow.FindControl("txtAddEmail") as TextBox;
            SqlDataSource2.InsertParameters["Name"].DefaultValue = txtAddName.Text;
            // SqlDataSource2.InsertParameters["Email"].DefaultValue = txtAddEmail.Text;
            SqlDataSource2.Insert();

            // ExecuteInsert(txtAddName.Text);

            txtAddName.Text = "";
            txtAddEmail.Text = "";
        }


        public string GetConnectionString()
        {
            //sets the connection string from your web config file "ConnString" is the name of your Connection String
            return System.Configuration.ConfigurationManager.ConnectionStrings["ZSC_WorkOrdersConnectionString"].ConnectionString;
        }

        public void bindgridView()
        {
            try
            {

               SqlConnection conn = new SqlConnection(GetConnectionString());


                string query = "Select * WO_ID, Name, Job_Type, Job_UpdateName, Job_Title, Job_Description, Job_Assigned_To, Completed, Completed_Date, Notes FROM WO_Submission_Details";
                DataSet ds = new DataSet();

                SqlDataAdapter sqldt = new SqlDataAdapter(query, conn);
                sqldt.Fill(ds);

                GridViewAdmin.DataSource = ds;
                GridViewAdmin.DataBind();



                if (ViewState["delRows"] != null)
                {

                    int[] delIndices = (int[])ViewState["delRows"];

                    int itemsLength = delIndices.Count(indx => indx != 0);

                    //create the javascript array in the client side
                    //push the deleted row indexes from c# array to javascript array
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<script>");
                    sb.Append("var indexArray = new Array;");
                    for (int i = 0; i < itemsLength; i++)
                    {
                        sb.Append("indexArray.push('" + delIndices[i] + "');");
                    }
                    sb.Append("</script>");

                    ClientScript.RegisterStartupScript(this.GetType(), "arrayScript", sb.ToString());

                    //call the deleteRow function on the client side
                    this.ClientScript.RegisterStartupScript(typeof(Page), "del", "javascript:deletegrdvwRow()", true);
                }


            }
            catch (Exception)
            { }
        }


        protected void GridViewAdmin_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridViewAdmin.EditIndex = e.NewEditIndex;

        }


        protected void GridViewAdmin_RowCancelingEdit(object sender, EventArgs e)
        {

            GridViewAdmin.EditIndex = -1;

        }


        protected void GridViewAdmin_RowCreated(object sender, GridViewRowEventArgs e)
        {

            foreach (TableCell cell in e.Row.Cells)
            {
                if (!string.IsNullOrEmpty(cell.Text) && cell.Text != "&nbsp;")
                {
                    BoundField field = (BoundField)((DataControlFieldCell)cell).ContainingField;
                    if ((field.DataField != "Job_Assigned_To") && (field.DataField != "Completed") && (field.DataField != "Completed_Date") && (field.DataField != "Notes"))
                        field.ReadOnly = true;
                }
            }


        }



        protected void GridViewAdmin_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {

                GridViewAdmin.PageIndex = e.NewPageIndex;
                //while moving to the next page, clear the viewstate
                ViewState["delRows"] = null;



            }
            catch (Exception)
            { }
        }


        protected void GridViewAdmin_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            try
            {

                GridViewRow row = (GridViewRow)GridViewAdmin.Rows[e.RowIndex];
                //i set datakeys="ProductName,ProductID" in gridview in aspx page
                //datakeys[rowindex][1]->refers to productid which is primary key.
                string WOID = GridViewAdmin.DataKeys[row.RowIndex][0].ToString();
                SqlConnection conn = new SqlConnection(GetConnectionString());
                TextBox JobAssignedTo = (TextBox)row.FindControl("txtJobAssignedTo");
                CheckBox txtCompleted = (CheckBox)row.Cells[1].Controls[0];
                TextBox CompletedDate = (TextBox)row.Cells[2].Controls[0];
                TextBox Notes = (TextBox)row.Cells[3].Controls[0];



                //write your logic here to update the data into the database
                conn.Open();
                SqlCommand cmd = new SqlCommand("update WO_Submission_Details set Job_Assigned_To='" + JobAssignedTo.Text + "',Completed='" + txtCompleted.Checked + "',Completed_Date='" + CompletedDate.Text + "',Notes='" + Notes.Text + "'where WO_ID='" + WOID + "'", conn);
                //SqlCommand cmd = new SqlCommand("update duplicating_request_table set Completed_By=@CompletedBy WHERE Job_No=@JobNo");
                cmd.ExecuteNonQuery();
                conn.Close();
                GridViewAdmin.EditIndex = -1;

                //those rows which are deleted previously while updating store it's indexs
                if (ViewState["delRows"] == null)
                {
                    int[] delIndices = new int[12];
                    delIndices[0] = e.RowIndex;
                    ViewState["delRows"] = delIndices;
                }
                else
                {
                    int[] delIndices = (int[])ViewState["delRows"];

                    int itemsLength = delIndices.Count(indx => indx != 0);

                    delIndices[itemsLength] = e.RowIndex;
                }



            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }


        }
    }

1 个答案:

答案 0 :(得分:0)

看起来您的SqlDataSource2导致错误。请仔细检查您的数据库中的名称和电子邮件是否为数据库类型字符串。

在ASPX SqlDataSource2中进行以下更改:

<InsertParameters>
    <asp:QueryStringParameter Name="Name" QueryStringField="Name" DbType=String />
    <asp:QueryStringParameter Name="Email" QueryStringField="Email" DbType=String />
</InsertParameters> 

在C#Code-Behind中,更改为:

SqlDataSource2.InsertParameters[0].DefaultValue = txtAddName.Text;