asp.net DataList选择DropDownList值

时间:2014-05-04 16:01:11

标签: c# asp.net sql datalist

我正在撰写有关文章发布的申请。我有2张桌子 “artikulli”

id                   int    Unchecked
tema                 varchar(250)   Checked
abstrakti            text   
data_publikimit      date   
path                 varchar(350)  
keywords             varchar(350)  
kategoria_id         int   
departamenti_id      int   

“kategorite”

id          int Unchecked
emertimi    varchar(350)    

我想在下拉列表中显示字段“emertimi”的所有值,以及当用户选择一个值以在表“artikulli”中保存该值的id时。 我已经完成了以下操作,但是我遇到了语法问题,因为我使用的是DATALIST。

public partial class AddArticle : System.Web.UI.Page
{
    string connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringDatabase"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        Page.Form.Attributes.Add("enctype", "multipart/form-data");
        try
        {

            if (!IsPostBack)
            {

                Bind();
            }

        }
        catch (Exception ex)
        {
            Response.Write("Error:" + ex.ToString());

        }
    }

    public void Bind()
    {
        SqlConnection con = new SqlConnection(connection)
        string Qry = "select * from kategoria";
        SqlDataAdapter da = new SqlDataAdapter(Qry, con);
        DataSet ds = new DataSet();
        DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
        con.Open();
        da.Fill(ds);
        drpdKategoria.DataSource = ds;
        drpdKategoria.DataValueField = "id";  // Value of bided list in your dropdown in your case it will be CATEGORY_ID
        drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
        drpdKategoria.DataBind();
        con.Close();
        con.Dispose();
        ds.Dispose();
        da.Dispose();  
    }

    protected void datalist2_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("Insert"))
        {
            TextBox txtTema = e.Item.FindControl("txtTema") as TextBox;
            TextBox txtAbstrakti = e.Item.FindControl("txtAbstrakti") as TextBox;
            TextBox txtData = e.Item.FindControl("txtData") as TextBox;
            TextBox txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
            DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;

            SqlConnection conn = new SqlConnection(connection);
            SqlCommand command = new SqlCommand();
            command.Connection = conn;
            command.CommandText = "Insert into artikulli(tema,abstrakti,data_publikimit,path,keywords,kategoria_id) values (@tema,@abstrakti,@data,@filename,@keywords,@kategoria)";
            command.Parameters.Add(new SqlParameter("@tema", txtTema.Text));
            command.Parameters.Add(new SqlParameter("@abstrakti", txtAbstrakti.Text));
            command.Parameters.Add(new SqlParameter("@data", txtData.Text));
            command.Parameters.Add(new SqlParameter("@keywords", txtKeywords.Text));
            command.Parameters.Add(new SqlParameter("@kategoria", drpdKategoria.SelectedValue));

            FileUpload FileUploadArtikull = (FileUpload)e.Item.FindControl("FileUploadArtikull");

            if (FileUploadArtikull.HasFile)
            {
                int filesize = FileUploadArtikull.PostedFile.ContentLength;
                if (filesize > 4194304)
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Maximumi i madhesise se file qe lejohet eshte 4MB');", true);
                }
                else
                {
                    string filename = "artikuj/" + Path.GetFileName(FileUploadArtikull.PostedFile.FileName);
                    //add parameters
                    command.Parameters.AddWithValue("@filename", filename);

                    conn.Open();
                    command.ExecuteNonQuery();
                    conn.Close();
                    Bind();

                    FileUploadArtikull.SaveAs(Server.MapPath("~/artikuj\\" + FileUploadArtikull.FileName));
                    Response.Redirect("dashboard.aspx");

                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "popup", "alert('Ju nuk keni ngarkuar asnje artikull');", true);
            }

        }

    }

AddArtikull.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddArtikull.aspx.cs" Inherits="AddArticle" MasterPageFile="~/MasterPage2.master" %>
   <asp:Content ID="content2" ContentPlaceholderID=ContentPlaceHolder2 runat="server">
       <asp:DataList ID="datalist2" runat="server" 
           onitemcommand="datalist2_ItemCommand" >
            <FooterTemplate> 
            <section id="main" class="column"  runat="server" style="width:900px;"> 
                 <article class="module width_full" style="width:900px;">
                <header><h3 style="text-align: center">Shto Artikull&nbsp;</h3></header>
            <div id="Div1" class="module_content" runat="server">         
                <asp:Label ID="Label1" runat="server" style="font-weight: 700">Tema</asp:Label>
                <fieldset>           
                    <asp:TextBox  ID="txtTema" runat="server"></asp:TextBox>
                    &nbsp;&nbsp;
                    <asp:RequiredFieldValidator ID="RequiredFieldValidatorTema" runat="server" 
                        ControlToValidate="txtTema" Display="Dynamic" 
                        ErrorMessage="Kjo fushe eshte e nevojshme" style="color: #CC0000"></asp:RequiredFieldValidator>
                </fieldset><br />
                &nbsp;<asp:Label ID="Label6" runat="server" style="font-weight: 700">Abstrakti</asp:Label>
                <fieldset>
                <asp:TextBox  ID="txtAbstrakti" style="height:250px;" Textmode="Multiline" runat="server"></asp:TextBox>                 
                    &nbsp;&nbsp;
                    <asp:RequiredFieldValidator ID="RequiredFieldValidatorAbstrakti" runat="server" 
                        ControlToValidate="txtAbstrakti" ErrorMessage="Kjo fushe eshte e nevojshme" 
                        style="color: #CC0000"></asp:RequiredFieldValidator>
                </fieldset>
                <asp:Label ID="lblData" runat="server" style="font-weight: 700">Data e Publikimit</asp:Label>
                <fieldset>
                    <asp:TextBox  ID="txtData" runat="server"></asp:TextBox>                   
                </fieldset>
                <asp:Label ID="lblKeywords" runat="server" style="font-weight: 700">Keywords</asp:Label>
                <fieldset>
                    <asp:TextBox  ID="txtKeywords" runat="server"></asp:TextBox>                   
                </fieldset>
                <br />

                <asp:Label ID="Label5" runat="server" style="font-weight: 700">Kategoria</asp:Label>
                <div>
                    <asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
                    <asp:Button ID="Button1" runat="server" Text="Insert" 
                      />
                </div><br /> 
                <strong>Ngarko Artikull</strong><br />
                <asp:FileUpload ID="FileUploadArtikull" runat="server" /><br />
                <br />             
                    <asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />
                    </div> 
                    </article> 
                </section> 
        </FooterTemplate>
       </asp:DataList>
  </asp:Content>

显示此错误:

  

编译器错误消息:CS0103:名称“e”不存在于   目前的背景   在这一行:

 DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;

1 个答案:

答案 0 :(得分:0)

在bind方法中,您调用的是不存在的对象e。如果下拉列表不在绑定元素内,则可以直接引用前面的代码,例如

drpdKategoria.DataSource = ds;
drpdKategoria.DataValueField = "id";  // Value of bided list in your dropdown in your case it will be CATEGORY_ID
drpdKategoria.DataTextField = "emertimi"; // this will show Category name in your dropdown
drpdKategoria.DataBind();

只要它是runat =“server”

就找不到控件

更新

好的,所以你需要在你的datalist中添加一个OnItemCreated事件

OnItemCreated="datalist2_OnItemCreated"

然后在那个方法中你需要这个

protected void datalist2_OnItemCreated(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Footer)
    {
        DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
        SqlConnection con = new SqlConnection(connection)
        string Qry = "select * from kategoria";
        SqlDataAdapter da = new SqlDataAdapter(Qry, con);
        DataSet ds = new DataSet();
        con.Open();
        da.Fill(ds);
        drpdKategoria.DataSource = ds;
        drpdKategoria.DataValueField = "id";
        drpdKategoria.DataTextField = "emertimi";
        drpdKategoria.DataBind();
        con.Close();
        con.Dispose();
        ds.Dispose();
        da.Dispose(); 
    }
}

如果您只有页脚,那么这将有效,如果您添加一个itemtemplate,那么您只需要删除对页脚的检查,并在每个项目创建时抓取该项目的下拉列表