0

我是 ASP.NET 的新手

错误:“FormView 'FormView1' 触发了未处理的事件 ItemInserting。”

我有一个 FormView 在页面首次加载时设置为插入模式。我还想预先填充这些输入文本框和下拉列表中的值。因此,我能够通过使用后面的代码并将值写入这些框来使其工作,但是当我单击“插入”链接按钮时,它给了我这个错误。

这是我的 FormView 代码:

        <asp:FormView ID="FormView1" DefaultMode="Insert" runat="server"
            DateSourceID="dsApprovedCreateNew"
            DataKeyNames="ApprovedID"
        > 
            <InsertItemTemplate> 

            <table class="FormDetail" width="95%" height="100%" align="center" class="FormDetail" > 
            <tr>
                <td class="right">MDF Name:</td>
                <td>
                    <asp:TextBox ID="MDFName" runat="server" Width="50%" Text='<%# Bind("MDFName") %>'  > </asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
                    ControlToValidate="MDFName"  Text="The MDFName field is required!" runat="server" />

                </td>
            </tr>
            <tr>
                <td>Vendor Name</td>
                <td>
                    <asp:DropDownList ID="ddlVendorList" runat="server"></asp:DropDownList>

                </td>
            </tr>
            <tr>
                <td>Vendor BU</td>
                <td>
                    <asp:DropDownList ID="ddlVendorBUList" runat="server"></asp:DropDownList>

                </td>
            </tr>
            <tr>
                <td class="right">Vendor Quarter:</td>
                <td>
                    <asp:DropDownList ID="VendorQuarter" runat="server"  Text='<%# Bind("VendorQuarter") %>'
                    AppendDataBoundItems="true">
                        <asp:ListItem Value="Q1">Q1</asp:ListItem>
                        <asp:ListItem Value="Q2">Q2</asp:ListItem>
                        <asp:ListItem Value="Q3">Q3</asp:ListItem>
                        <asp:ListItem Value="Q4">Q4</asp:ListItem>
                 </asp:DropDownList>
                </td>
            </tr>

            <tr>
                <td class="right">MDF Amount:</td>
                <td>
                    <asp:TextBox ID="MDFAmount" runat="server" Width="20%" TextMode="SingleLine"  Text='<%# Bind("VendorQuarter") %>'></asp:TextBox>
                    <asp:CustomValidator ID="RangeValidator3" runat="server" ControlToValidate="MDFAmount" 
                    ErrorMessage="Enter numerical value only!"  ClientValidationFunction="validateNumber"/>
                    <asp:RequiredFieldValidator ControlToValidate="MDFAmount" Text="The MDFAmount field is required!" runat="server" />
                    <%--
                    <asp:RegularExpressionValidator ID="RangeValidator4" runat="server" ControlToValidate="MDFAmount" 
                    Display="Dynamic" ErrorMessage="*Enter numerical value only" 
                    ValidationExpression="^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$"/>
                    --%>
                </td>
            </tr>
            <tr>
                <td class="right">Begin Date (mm/dd/yyyy):</td>
                <td>
                    <asp:TextBox ID="BeginDate" runat="server" Width="50%" TextMode="SingleLine"  DataFormatString="{0:MM/dd/yyyy}"  
                        ApplyFormatInInsertMode="true"  ></asp:TextBox>
                    <asp:RegularExpressionValidator  ID="RangeValidator1" runat="server" ControlToValidate="BeginDate" ForeColor="Red"
                        ErrorMessage="Enter Valid Date in dd/mm/yyyy format." SetFocusOnError="True" Display="Dynamic" Type="Date"
                        ValidationExpression="^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$">
                    </asp:RegularExpressionValidator>


                </td>
            </tr>
            <tr>
                <td class="right">End Date (mm/dd/yyyy):</td>
                <td>
                    <asp:TextBox ID="EndDate" runat="server" Width="50%"></asp:TextBox>
                    <asp:RegularExpressionValidator  ID="RangeValidator2" runat="server" ControlToValidate="EndDate" ForeColor="Red"
                                ErrorMessage="Enter Valid Date in dd/mm/yyyy format." SetFocusOnError="True" Display="Dynamic" Type="Date"
                                ValidationExpression="^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$"/>
                </td>
            </tr>


            <tr>
                <td class="right">MDF Summary:</td>
                <td>
                    <asp:TextBox ID="MDFSummary" TextMode="MultiLine" Width="50%" Height="100" runat="server"></asp:TextBox>
                </td>
            </tr>
                        <tr>
                <td class="right">Status:</td>
                <td>
                    <asp:DropDownList ID="Status" runat="server"
                    AppendDataBoundItems="true">
                        <asp:ListItem>Active</asp:ListItem>
                        <asp:ListItem>Inactive</asp:ListItem>
                 </asp:DropDownList>
                </td>
            </tr>
            <tr>
              <td colspan="2">
                <asp:linkbutton id="InsertButton"
                  text="Insert"
                  commandname="Insert"
                  runat="server" />
                <asp:linkbutton id="CancelButton"
                  text="Cancel"
                  commandname="Cancel"
                  runat="server" /> 
              </td>
            </tr>          
        </table>

    <asp:HiddenField ID="CreatedBy" runat="server" value="44444"/> 
    </InsertItemTemplate>     
    </asp:FormView>    

 <asp:sqldatasource id="dsApprovedCreateNew"
        connectionstring="<%$ ConnectionStrings:ConnectionString%>" 
        SelectCommand="SELECT p.*
            , (SELECT VendorName FROM MDF_Vendor WHERE VendorID = p.VendorID) AS VendorName
            , (SELECT VendorBUName FROM MDF_VendorBU WHERE VendorBUID = p.VendorBUID) AS VendorBUName
            FROM dbo.MDF_Proposed p Where p.ProposedID = 63"
        InsertCommand = "INSERT INTO [MDF_Approved] ([VendorID], [VendorBUID], [MDFName]
            , [BeginDate], [EndDate], [CreatedBy]) 
             VALUES (@VendorID, @VendorBUID, @MDFName, @BeginDate, @EndDate, '1234') "

        runat="server">
        <SelectParameters>
            <asp:QueryStringParameter Name="ProposedID" QueryStringField="ProposedID"  runat="server" />
        </SelectParameters>
 </asp:sqldatasource>
 </form>

背后的代码(我是新手,所以不要嘲笑我的代码,欢迎提出建议)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

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

    protected void Page_Load(object sender, EventArgs e)
    {

        //FormView1.PreRender += FormView1_PreRender;
        //FormView1.DataBinding += FormView1_DataBinding;
        if (!IsPostBack)
        {
            //Response.Write("ProposedID: " + Request.QueryString["ProposedID"]);
            int ProposedID = FetchQueryStringIdentifierByKey("ProposedID");
            Response.Write("ProposedID : " + ProposedID);
            //FormView1.DataSource = this.GetData(ProposedID);
            //FormView1.DataBind();

            FillFormValues(ProposedID);

            //GetData(ProposedID);

        }     
    }

    protected int FetchQueryStringIdentifierByKey(string key)
    {
        int identifier;
        var isInt = int.TryParse(Request.QueryString[key], out identifier);
        return (isInt) ? identifier : 0;
    } 


    private DataSet GetData(int RecID)
    {
        string conString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string query = "SELECT * FROM MDF_Proposed WHERE ProposedID = 63";
        SqlCommand cmd = new SqlCommand(query);
        SqlParameter[] param = new SqlParameter[1];


        param[0] = new SqlParameter("@RecID", SqlDbType.Int, 10);
        param[0].Value = 1; // RecID;
        for (int i = 0; i < param.Length; i++)
        {
            cmd.Parameters.Add(param[i]);
        }
        using (SqlConnection con = new SqlConnection(GetConnectionString()))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    sda.Fill(ds);
                    return ds;

                }
            }
        }

    }

    private void FillFormValues(int RecID)
    {
        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT * FROM MDF_Proposed WHERE ProposedID = 63";
        cmd.Parameters.AddWithValue("@RecID", RecID);
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        con.Open();
        dAdapter.Fill(objDs);
        con.Close();
        if (objDs.Tables[0].Rows.Count > 0)
        {
            if (FormView1.CurrentMode == FormViewMode.Insert)
            {
                Response.Write("The Mode: " + FormView1.CurrentMode);
                TextBox MDFName = (TextBox)FormView1.FindControl("MDFName");
                MDFName.Text = objDs.Tables[0].Rows[0]["MDFName"].ToString();

                TextBox MDFAmount = (TextBox)FormView1.FindControl("MDFAmount");
                MDFAmount.Text = objDs.Tables[0].Rows[0]["MDFAmount"].ToString();

                TextBox BeginDate = (TextBox)FormView1.FindControl("BeginDate");
                BeginDate.Text = FormatDateNoTime(objDs.Tables[0].Rows[0]["BeginDate"].ToString());

                TextBox EndDate = (TextBox)FormView1.FindControl("EndDate");
                EndDate.Text = FormatDateNoTime(objDs.Tables[0].Rows[0]["EndDate"].ToString());

                fillVendorDLL(Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorID"]));
                fillVendorBUDLL(Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorID"]), Convert.ToInt32(objDs.Tables[0].Rows[0]["VendorBUID"]));

                TextBox MDFSummary = (TextBox)FormView1.FindControl("MDFSummary");
                MDFSummary.Text = objDs.Tables[0].Rows[0]["MDFSummary"].ToString();
            }
            else
            {
                Response.Write("Nothing");
            }
        }
        else
        {
            Response.Write("No Record found");
        }
    }


    protected void fillVendorDLL(int VendorID)
    {


        //DropDownList ddlVendor = (DropDownList)sender;
        // DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl("updateVendorName");

        //DropDownList ddlVendor = (DropDownList)sender;

        //DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl(ddlID);


        DropDownList ddlVendor =
            (DropDownList)FormView1.FindControl("ddlVendorList");


        if (ddlVendor != null)
        {
            //Response.Write("SelectChanged");
            //int VendorID = Convert.ToInt32(ddlVendor.SelectedValue.ToString());
            //Response.Write("VendorID: " + VendorID);

            ddlVendor.Items.Clear();

            string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT VendorID, VendorName FROM dbo.MDF_Vendor";
            cmd.Parameters.AddWithValue("@VendorID", VendorID);
            DataSet objDs = new DataSet();
            SqlDataAdapter dAdapter = new SqlDataAdapter();
            dAdapter.SelectCommand = cmd;
            con.Open();
            dAdapter.Fill(objDs);

            con.Close();

            if (objDs.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in objDs.Tables[0].Rows)
                {
                    ddlVendor.Items.Insert(0, new ListItem((dr["VendorName"]).ToString(), (dr["VendorID"]).ToString()));
                    ddlVendor.SelectedValue = Convert.ToString(VendorID);
                }
            }
        }
    }


    protected void fillVendorBUDLL(int VendorID, int VendorBUID)
    {


        //DropDownList ddlVendor = (DropDownList)sender;
        // DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl("updateVendorName");

        //DropDownList ddlVendor = (DropDownList)sender;

        //DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl(ddlID);


        DropDownList ddlVendorBU =
            (DropDownList)FormView1.FindControl("ddlVendorBUList");


        if (ddlVendorBU != null)
        {
            //Response.Write("SelectChanged");
            //int VendorID = Convert.ToInt32(ddlVendor.SelectedValue.ToString());
            //Response.Write("VendorID: " + VendorID);

            ddlVendorBU.Items.Clear();

            string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection con = new SqlConnection(strConn);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = @VendorID";
            cmd.Parameters.AddWithValue("@VendorID", VendorID);
            cmd.Parameters.AddWithValue("@VendorBUID", VendorBUID);
            DataSet objDs = new DataSet();
            SqlDataAdapter dAdapter = new SqlDataAdapter();
            dAdapter.SelectCommand = cmd;
            con.Open();
            dAdapter.Fill(objDs);

            con.Close();

            if (objDs.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow dr in objDs.Tables[0].Rows)
                {
                    ddlVendorBU.Items.Insert(0, new ListItem((dr["VendorBUName"]).ToString(), (dr["VendorBUID"]).ToString()));
                    ddlVendorBU.SelectedValue = Convert.ToString(VendorBUID);
                }
            }
        }
    }

    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["ConnectionString"].ConnectionString;
    }   

    private void ExecuteInsert(string VendorName, string VendorBU, string MDFAmount
    , string StartDate, string EndDate, string VendorQuarter, string MDFName, String MDFSummary, string Status, string CreatedBy)
        {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        string sql = "INSERT INTO MDF_Proposed (VendorID, VendorBUID, MDFAmount, BeginDate, EndDate, VendorQuarter
            , MDFName, MDFSummary, Status, CreatedBy) VALUES "
             + " (@VendorID, @VendorBUID, @MDFAmount, @StartDate, @EndDate, @VendorQuarter, @MDFName, @MDFSummary, @Status, @CreatedBy)";

        try
        {

            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlParameter[] param = new SqlParameter[10];

            param[0] = new SqlParameter("@VendorID", SqlDbType.VarChar, 50);
            param[1] = new SqlParameter("@VendorBUID", SqlDbType.VarChar, 50);
            param[2] = new SqlParameter("@MDFAmount", SqlDbType.Decimal);
                param[2].Precision = 19;
                param[2].Scale = 4;
            param[3] = new SqlParameter("@StartDate", SqlDbType.DateTime);
            param[4] = new SqlParameter("@EndDate", SqlDbType.DateTime);
            param[5] = new SqlParameter("@VendorQuarter", SqlDbType.VarChar, 50);
            param[6] = new SqlParameter("@MDFName", SqlDbType.VarChar, 50);
            param[7] = new SqlParameter("@MDFSummary", SqlDbType.VarChar, 2000);
            param[8] = new SqlParameter("@Status", SqlDbType.VarChar, 50);
            param[9] = new SqlParameter("@CreatedBy", SqlDbType.Int, 10);

            param[0].Value = VendorName;
            param[1].Value = VendorBU;
            param[2].Value = MDFAmount;
            param[3].Value = StartDate;
            param[4].Value = EndDate;
            param[5].Value = VendorQuarter;
            param[6].Value = MDFName;
            param[7].Value = MDFSummary;
            param[8].Value = Status;
            param[9].Value = CreatedBy;

            for (int i = 0; i < param.Length; i++)
            {
                cmd.Parameters.Add(param[i]);
            }

            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
            //ClientScript.RegisterStartupScript(this.GetType(), "scriptid", window.parent.location.href='ViewVendors.aspx'", true);
            Response.Write("<script>window.parent.location = 'ProposalListView.aspx';</script>");
            //Response.Redirect("ProposalListView.aspx");
            //Response.Write("<script>this.dialog('close');</script>");
        }
    }


    public static void ClearControls(Control Parent){

        if (Parent is TextBox)
        { (Parent as TextBox).Text = string.Empty; }
        else
        {
            foreach (Control c in Parent.Controls)
                ClearControls(c);
        }
    }

    public string FormatDateNoTime(string input)
    {
        string thedate;
        DateTime strDate = DateTime.Parse(input);
        thedate = strDate.ToString("MM/dd/yyyy");
        return thedate;
    }
}
4

1 回答 1

5

您还可以使用 DataBound 事件:

protected void FormView1_DataBound(object sender, EventArgs e)
    {
        if (FormView1.CurrentMode == FormViewMode.Insert)
        {
            var textBox = (TextBox) FormView1.FindControl("MyTextBox");
            textBox.Text = "Default Value";
        }
    }
于 2013-09-09T17:40:55.457 回答