dropdownlist name有一个SelectedValue,它是无效的,因为它在项列表中不存在

时间:2014-05-28 03:32:57

标签: c# asp.net gridview drop-down-menu updates

我想要实现的是当我点击编辑时,gridview中的Blogtype字段将更改为dropdownlist。由于我的数据库在博客类型中有3个数据,即社区工作,竞争和海外经验。下拉列表将允许我选择这三个中的任何一个。选择这一个之后,我点击了更新,它将在数据库中更新。怎么做,因为我在第3个屏幕截图中有错误。我的blogtype字段的下拉列表的名称是ddlBlogType。帮助

enter image description here

enter image description here

但对于我当前的代码,点击编辑后会出现此错误。 ' ddlBlogType'具有一个无效的SelectedValue,因为它不存在于项列表中。 参数名称:value enter image description here

源代码

<asp:GridView ID="grdBlog" runat="server" style=
"margin-left: 0px" Width="1000px" Height="147px" AutoGenerateColumns="False" 
                        onrowcancelingedit="grdBlog_RowCancelingEdit" onrowediting="grdBlog_RowEditing" 
                        onrowupdating="grdBlog_RowUpdating" DataKeyNames="BlogID" 
                        onrowdeleting="grdBlog_RowDeleting" AllowPaging="True" 
                        onpageindexchanging="grdBlog_PageIndexChanging" PageSize="5" 
            BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" 
            CellPadding="3" CellSpacing="1" GridLines="None" >
                        <Columns>
                            <asp:BoundField DataField="BlogID" HeaderText="BlogID" ReadOnly="true" 
                                SortExpression="BlogID" />
                            <asp:TemplateField HeaderText="Name">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtName" runat="server" Width="80px" Text='<%# Bind("Name") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="BlogType">
                                <EditItemTemplate>
                                    <asp:DropDownList ID="ddlBlogType" runat="server" Width="80px" Text='<%# Bind("BlogType") %>'></asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Description">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtDescription" runat="server" Width="80px" Text='<%# Bind("Description") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="DateEntry" HeaderText="Date Entry" ReadOnly="true" />
                            <asp:TemplateField HeaderText="Blog Story">
                                <EditItemTemplate>
                                    <asp:TextBox ID="txtBlogStory" runat="server" TextMode="multiline" rows="10" Text='<%# Bind("BlogStory") %>'></asp:TextBox>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("BlogStory") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>
                            <asp:BoundField DataField="modifiedby" HeaderText="Last Modified By" ReadOnly="true" />
                            <asp:BoundField DataField="modifieddate" HeaderText="Last Modified Date" ReadOnly="true" />
                            <asp:CommandField ShowEditButton="True" CausesValidation="false" />
                            <asp:TemplateField ShowHeader="False">
                                <ItemTemplate>
                                    <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" 
                                        CommandName="Delete" Text="Delete" OnClientClick="javascript : return confirm('Confirm delete this record?');"></asp:LinkButton>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                        <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
                        <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
                        <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
                        <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
                        <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
                        <SortedAscendingCellStyle BackColor="#F1F1F1" />
                        <SortedAscendingHeaderStyle BackColor="#594B9C" />
                        <SortedDescendingCellStyle BackColor="#CAC9C9" />
                        <SortedDescendingHeaderStyle BackColor="#33276A" />
                    </asp:GridView>

代码背后的代码

if (Page.IsPostBack == false)
        {
            bindResultGridView();

        }

 private void bindResultGridView()
    {
        String ConStr = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(ConStr);

        try
        {

            String SQL = null;

            SQL = "SELECT BlogID, Name, Blogtype, Description, convert(varchar,Dateentry, 103) as Dateentry, BlogStory, modifiedby, convert(varchar,modifieddate, 103) as modifieddate FROM [EntryTable] ORDER BY BlogID DESC";

            SqlCommand cmd = new SqlCommand(SQL, con);
            con.Open();

            SqlDataReader reader = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(reader);
            grdBlog.DataSource = dt;
            grdBlog.DataBind();


            reader.Close();
        }

        finally
        {
            con.Close();
        }
    }

 protected void grdBlog_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdBlog.EditIndex = -1;
        bindResultGridView();
    }

    protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdBlog.EditIndex = e.NewEditIndex;
        bindResultGridView();
    }
    protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int selectedRow = e.RowIndex;   //get selected row
        //  get product id from data key
        int blogid = (int)grdBlog.DataKeys[selectedRow].Value;

        //  get current grid view row
        GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
        TextBox name = (TextBox)row.FindControl("txtName");
        //  find text box for txtPrice
        DropDownList blogtype = (DropDownList)row.FindControl("ddlBlogType");
        TextBox description = (TextBox)row.FindControl("txtDescription");
        TextBox blogstory = (TextBox)row.FindControl("txtBlogStory");
        //  Remove $ sign
        string strName = name.Text;
        string strBlogType = blogtype.Text;
        string strDescription = description.Text;
        string strBlogStory = blogstory.Text;
        /*
        DateTime datDate;
        */

        /*
        if (DateTime.TryParseExact(strDateEntry, new string[] { "dd/MM/yyyy" },
                               System.Globalization.CultureInfo.InvariantCulture,
                               System.Globalization.DateTimeStyles.None, out datDate))
        {
         */
            updateBlogGridviewRecord(blogid, strName, strBlogType, strDescription, strBlogStory);
        /*
        }

        else
        {
            lblError.Visible = true;
            lblError.Text = "Invalid Date";
            lblSuccess.Visible = false;
        }
        */
    }

        private void updateBlogGridviewRecord(int blogid, string strName, string strBlogType, string strDescription, string strBlogStory)
        {
            try
            {
                string strConnectionString = ConfigurationManager.ConnectionStrings["BlogConnectionString"].ConnectionString;
                SqlConnection myConnect = new SqlConnection(strConnectionString);

                string strCommandText = "UPDATE EntryTable SET [ModifiedBy]=@Modifier, [ModifiedDate] = GETDATE(), [Name]=@Name, [BlogType]=@BlogType, [Description]=@Description, [BlogStory]=@BlogStory WHERE [BlogID]=@BlogID";
                /*string strCommandText = "UPDATE EntryTable SET [Name]=@Name, [BlogType]=@BlogType, [Description]=@Description, [DateEntry]=@DateEntry, [BlogStory]=@BlogStory WHERE [BlogID]=@BlogID"; */
                /*string strCommandText = "UPDATE EntryTable SET [ModifiedBy] = [Name], [Name]=@Name, [BlogType]=@BlogType, [Description]=@Description, [DateEntry]=@DateEntry, [BlogStory]=@BlogStory WHERE [BlogID]=@BlogID"; */

                SqlCommand cmd = new SqlCommand(strCommandText, myConnect);
                cmd.Parameters.AddWithValue("@BlogID", blogid);
                cmd.Parameters.AddWithValue("@Name", strName);
                cmd.Parameters.AddWithValue("@BlogType", strBlogType);
                //cmd.Parameters.AddWithValue("@DateEntry", datDate);
                cmd.Parameters.AddWithValue("@Description", strDescription);
                cmd.Parameters.AddWithValue("@BlogStory", strBlogStory);
                cmd.Parameters.AddWithValue("@Modifier", Session["Username"]);
                myConnect.Open();

                int result = cmd.ExecuteNonQuery();

                if (result > 0)
                {
                    lblSuccess.Visible = true;
                    lblSuccess.Text = "Record updated!";
                    lblError.Visible = false;
                }
                else
                {
                    lblSuccess.Visible = true;
                    lblError.Text = "Update fail";
                    lblError.Visible = false;
                }

                myConnect.Close();


                //Cancel Edit Mode
                grdBlog.EditIndex = -1;
                bindResultGridView();
            }

            catch
            {
                lblError.Visible = true;
                lblError.Text = "Invalid Data";
                lblSuccess.Visible = false;
            }
        }

是否使用下面的编辑代码

源代码

                            <asp:TemplateField HeaderText="BlogType">
                                <EditItemTemplate>
                                <asp:DropDownList ID="ddlBlogType" runat="server" DataTextField="ddlBlogType" DataValueField="ddlBlogType" SelectedValue='<%# Eval("blogType") %>'>                                                                 
                                    <asp:ListItem Enabled="true" Text="Community Work" Value="Community Work"></asp:ListItem>
                                    <asp:ListItem Text="Competition" Value="Competition"></asp:ListItem>
                                    <asp:ListItem Text="Overseas Experience" Value="Overseas Experience"></asp:ListItem>
                                </asp:DropDownList>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:Label ID="Label2" runat="server" Text='<%# Bind("BlogType") %>'></asp:Label>
                                </ItemTemplate>
                            </asp:TemplateField>

代码背后的代码

 protected void grdBlog_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int selectedRow = e.RowIndex;   //get selected row
        //  get product id from data key
        int blogid = (int)grdBlog.DataKeys[selectedRow].Value;

        //  get current grid view row
        GridViewRow row = (GridViewRow)grdBlog.Rows[selectedRow];
        TextBox name = (TextBox)row.FindControl("txtName");
        //  find text box for txtPrice
        DropDownList blogtype = (DropDownList)row.FindControl("ddlBlogType");
        TextBox description = (TextBox)row.FindControl("txtDescription");
        TextBox blogstory = (TextBox)row.FindControl("txtBlogStory");
        //  Remove $ sign
        string strName = name.Text;
        string strBlogType = blogtype.SelectedValue;
        string strDescription = description.Text;
        string strBlogStory = blogstory.Text;
    }

1 个答案:

答案 0 :(得分:0)

我将问题视为填充DropDownList的方式。代码未显示在您的帖子中,因此假设您没有任何相关内容。

因此,您通常在编辑模式下设置所需的gridviewrow,如下所示:

protected void grdBlog_RowEditing(object sender, GridViewEditEventArgs e)
{
    grdBlog.EditIndex = e.NewEditIndex;
    bindResultGridView();
}

现在我们需要确定何时绑定下拉列表。因此,当特定数据行(处于编辑模式)获得数据绑定时,我们有机会获得对相应编辑行的下拉列表的引用。因此,您可以参考this帖子。

总之,您需要处理gridview的DataBound事件,并从其rowstate确定它所处的模式。从以下链接的帖子共享代码示例:

protected void gv_RowDataBound(object sender, GridViewEditEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            DropDownList ddList= (DropDownList)e.Row.FindControl("DStatusEdit");
            //bind dropdownlist
            DataTable dt = con.GetData("select distinct status from directory");
            ddList.DataSource = dt;
            ddList.DataTextField = "YourCOLName";
            ddList.DataValueField = "YourCOLName";
            ddList.DataBind();

            DataRowView dr = e.Row.DataItem as DataRowView;
            //ddList.SelectedItem.Text = dr["YourCOLName"].ToString();
            ddList.SelectedValue = dr["YourCOLName"].ToString();
        }
   }
}