显示动态下拉值

时间:2014-05-03 18:45:43

标签: c# asp.net sql

我正在制作一个表格来插入有关文章的数据。我有一个名为“文章”和其他“类别”的表。在表文章中有一行名为categories_id,其中包含特定类别的ID。在我的表格中,我有一个名为“类别”的字段,即下拉列表。我正在使用DataList。我想要的是在该下拉列表中显示表“类别”中的所有类别,当用户选择其中一个时,在表“文章”中保存相应的id类别。在PHP中,我使用关联数组,但在这里我真的不知道该怎么做,因为我是这种语言的新手。

  <fieldset>
        <asp:DropDownList ID="DrpdKategoria" runat="server"> </asp:DropDownList>
  </fieldset>               
 <asp:Button ID="btnInsert" runat="server" CommandName="Insert" Text="Shto" />


  public partial class AddArticle : System.Web.UI.Page
    {
        string connection = n                 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);
            SqlDataAdapter da = new SqlDataAdapter("select * from artikulli", con);
            DataSet ds = new DataSet();
            con.Open();
            da.Fill(ds);
            con.Close();
            datalist2.DataSource = ds.Tables[0];
            datalist2.DataBind();
        }

        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 txtKeywords = e.Item.FindControl("txtKeywords") as TextBox;
                TextBox txtKategoria = e.Item.FindControl("txtKategoria") as TextBox;
                SqlConnection conn = new SqlConnection(connection);
                SqlCommand command = new SqlCommand();
                command.Connection = conn;
                command.CommandText = "Insert into artikulli(tema,abstrakti,path,keywords,kategoria_id) values (@tema,@abstrakti,@filename,@keywords,@kategoria)";
                command.Parameters.Add(new SqlParameter("@tema", txtTema.Text));
                command.Parameters.Add(new SqlParameter("@abstrakti", txtAbstrakti.Text));
                command.Parameters.Add(new SqlParameter("@keywords", txtKeywords.Text));
                command.Parameters.Add(new SqlParameter("@kategoria", txtKategoria.Text));

                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('ERROR');", true);
                }

            }

        }
    }

我的表artikulli有这个字段:

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

表kategoria有以下字段:

id          int Unchecked
emertimi    varchar(350)    Checked

我想从字段“emertimi”获取类别名称并在下拉列表中显示,但是每个名称都有id的索引,当选择其中一个时,要在字段“kategoria_id”中保存id

1 个答案:

答案 0 :(得分:0)

这只是一个示例程序,请自己处理SQL注入。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="drpdKategoria" runat="server" AutoPostBack="false"></asp:DropDownList>
        <asp:Button ID="btnInsert" runat="server" Text="Insert" 
            onclick="btnInsert_Click" />
    </div>
    </form>
</body>
</html>

和.cs页面鳕鱼是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=E:\\My Projects\\practice\\asp.net\\drpdTest\\App_Data\\Database.mdf;Integrated Security=True;User Instance=True");
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindCategory();
        }
    }

    private void ConnectionStatus()  // Checking connection Status either it is open or not
    {
        if (ConnectionState.Closed == con.State)
        {
            try
            {
                con.Open();
            }
            catch (SqlException ex)
            {
                Response.Write("<script language= 'JavaScript'> alert('" + ex.Message + "')</script>");
            }
        }
    }

    private void bindCategory()  // binding data to DropDownList
    {
        ConnectionStatus();
        string Qry = "select * from category";
        SqlDataAdapter da = new SqlDataAdapter(Qry, con);
        da.Fill(ds);
        drpdKategoria.DataSource = ds;
        drpdKategoria.DataValueField = "category_id";  // Value of bided list in your dropdown in your case it will be CATEGORY_ID
        drpdKategoria.DataTextField = "category_name"; // this will show Category name in your dropdown
        drpdKategoria.DataBind();
        con.Close();
        con.Dispose();
        ds.Dispose();
        da.Dispose();
    }
    private void insertData()
    {
        ConnectionStatus();  // Checking connection state either it is open or not.
        string Qry = "insert into article (categories_id) values('"+drpdKategoria.SelectedValue+"')";
        SqlCommand cmd = new SqlCommand(Qry, con);
        try
        {
            SqlDataReader dr = cmd.ExecuteReader();
            Response.Write("<script language= 'JavaScript'> alert('Record Inserted Please Check Your table')</script>");
            con.Close();
            con.Dispose();
        }
        catch (SqlException ex)
        {
            Response.Write("<script language= 'JavaScript'> alert('" + ex.Message + "')</script>");
        }

    }
    protected void btnInsert_Click(object sender, EventArgs e)
    {
        insertData();
    }
}