asp.net DataList选择下拉列表值

本文关键字:下拉列表 选择 DataList net asp | 更新日期: 2023-09-27 18:01:48

我正在申请文章发布。我有两张桌子"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;

asp.net DataList选择下拉列表值

在你的bind方法中,你正在调用一个不存在的对象。如果下拉列表不在绑定元素中,你可以直接引用前面的代码,例如

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"

更新

好的,你需要在你的数据列表中添加一个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那么你只需要去掉页脚的复选框然后在每个项目创建的时候为该项目抓取下拉列表