我希望在通过级联下拉列表过滤后编辑gridview

时间:2016-08-19 14:30:52

标签: asp.net gridview edit cascade

在2个级联下拉列表中,第二个是从产品中选择不同的 book_author ,其中 cat_id (类别 - 不是主键)与在第一次下拉。表产品有主键book_id,cat_id, book_author .. 2个下拉列表是ddlcat和ddlauthor

我希望完整的代码作为答案

<asp:DropDownList ID="ddlcat" runat="server" AutoPostBack="true" BackColor="White" ForeColor="Black" Height="30px" Width="100px" OnSelectedIndexChanged="ddlcat_SelectedIndexChanged">
            <asp:ListItem Text = "--Select Category--" Value = ""></asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="ddlauthor"  AutoPostBack="True" runat="server" Height="30px" Width="200px"  OnSelectedIndexChanged="ddlauthor_SelectedIndexChanged">
            <asp:listitem value="" text="--Select Author--" ></asp:listitem>
        </asp:DropDownList>

aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ddlcat.AppendDataBoundItems = true;
        String strConnString = ConfigurationManager
            .ConnectionStrings["abcd2"].ConnectionString;
        String strQuery = "select cat_id, cat_name from Category";
        SqlConnection con = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strQuery;
        cmd.Connection = con;
        try
        {
            con.Open();
            ddlcat.DataSource = cmd.ExecuteReader();
            ddlcat.DataTextField = "cat_name";
            ddlcat.DataValueField = "cat_id";
            ddlcat.DataBind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }
    }
}
protected void ddlcat_SelectedIndexChanged(object sender, EventArgs e)
{
    ddlauthor.Items.Clear();
    ddlauthor.Items.Add(new ListItem("--Select Author--", ""));


    ddlauthor.AppendDataBoundItems = true;
    String strConnString = ConfigurationManager
        .ConnectionStrings["abcd2"].ConnectionString;
    String strQuery = "select DISTINCT book_author FROM Products " +
                       "WHERE cat_id=@cat_id";
    SqlConnection con = new SqlConnection(strConnString);
    SqlCommand cmd = new SqlCommand();
    cmd.Parameters.AddWithValue("@cat_id",
        ddlcat.SelectedItem.Value);
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = strQuery;
    cmd.Connection = con;

    try
    {
        con.Open();
        ddlauthor.DataSource = cmd.ExecuteReader();
        ddlauthor.DataTextField = "book_author";
        ddlauthor.DataValueField = "book_author";

    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
}

0 个答案:

没有答案