Question

I am making an application about article publication. I have 2 tables "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)    

I want to display in a dropdown list all values of field "emertimi" and when the user selects one value to save id of that value in table "artikulli". I have done the following, but I have the problem with syntax because I am using 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>

It shows this error:

Compiler Error Message: CS0103: The name 'e' does not exist in the current context In this line:

 DropDownList drpdKategoria = e.Item.FindControl("drpdKategoria") as DropDownList;
Was it helpful?

Solution

In your bind method you are calling an object e that doesn't exist. If the dropdownlist isn't inside a bound element, you can just reference the front code directly, e.g.

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();

without finding the control as long as it is runat="server"

UPDATE

Okay, so you need to add an OnItemCreated event in your datalist

OnItemCreated="datalist2_OnItemCreated"

Then in that method you need this

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(); 
    }
}

That will work for if you only have the footer, if you add an itemtemplate then you just need to get rid of the check for the footer and on each item creation grab that dropdownlist for that item

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top