显示动态下拉值

本文关键字:动态 显示 | 更新日期: 2023-09-27 18:01:36

我正在制作一个表单来插入关于文章的数据。我有一个名为"文章"和其他"类别"的表。在表articles中,有一个名为categores_id的行,其中包含特定类别的id。在我的表单中,我有一个名为"类别"的字段,这是下拉。我正在使用数据列表。我想要的是显示所有类别从表"类别"下拉,当用户选择其中一个,在表"文章"保存相应的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

表类别有以下字段:

id          int Unchecked
emertimi    varchar(350)    Checked

我想从字段"emertimi"中获得类别的名称并在下拉列表中显示,但是对于每个名称都有id的索引,并且当选择其中一个时,将id保存在字段"categororia_id"

显示动态下拉值

这只是一个示例程序,请自己照顾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();
    }
}