Edgar Bots Ответов: 1

Как я могу сохранить данные с выбранным значением? Я могу сохранить данные в своей базе данных, но сохраненный-это идентификатор.


Моя проблема здесь заключается в том, что терминал и пункт назначения сохраняются как идентификатор. Как я могу это исправить? Спасибо за вашу помощь.

Это ListFieldStatusCodes и DropDownListStatusCodes_Selectedindexchanged

Вот cs моих кодов

Что я уже пробовал:

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

//add the following
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text.RegularExpressions;


public partial class TripInsert : System.Web.UI.Page
{

  
    string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
    DataSet ds = new DataSet();
    protected static System.IO.Stream fs;
    protected static System.IO.BinaryReader br;
    protected static Byte[] bytes;
    public class clsUIUtility
    {

        public static DataTable ExecuteQuery(string SQLstring)
        {
            string sConstr = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
            SqlConnection Conn = new SqlConnection(sConstr);
            DataTable dt = new DataTable("tbl");

            using (Conn)
            {
                Conn.Open();
                SqlCommand comm = new SqlCommand(SQLstring, Conn);
                comm.CommandTimeout = 0;
                SqlDataAdapter da = new SqlDataAdapter(comm);
                da.Fill(dt);
            }

            return dt;
        }

        public static void FillCombo(DropDownList dropDownList, string dataValueField, string dataTextField, DataTable dataTbl, bool bHasBlank)
        {
            dropDownList.DataTextField = dataTextField;
            dropDownList.DataValueField = dataValueField;
            dropDownList.DataSource = dataTbl;
            dropDownList.DataBind();

            if (bHasBlank)
                dropDownList.Items.Insert(0, new ListItem());
        }
    }
    
   
        

       


    private void ListFieldStatusCodes()
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string cmdstr = "SELECT TerminalID, Terminal FROM Terminal";
            SqlCommand cmd = new SqlCommand(cmdstr, connection);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            SqlDataReader rdr;
            DataTable dt = new DataTable("tbl");
            rdr = cmd.ExecuteReader();

            DropDownListStatusCodes.Items.Clear();

            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    DropDownListStatusCodes.Items.Add(rdr["Terminal"].ToString());
                }
            }
            DropDownListStatusCodes.DataSource = dt;
            DropDownListStatusCodes.DataTextField = "Terminal";
            DropDownListStatusCodes.DataValueField = "TerminalID";
            DropDownListStatusCodes.DataBind();
            clsUIUtility.FillCombo(DropDownListStatusCodes, "TerminalID", "Terminal", clsUIUtility.ExecuteQuery("SELECT TerminalID, Terminal FROM Terminal"), false);
            DropDownListStatusCodes.Items.Insert(0, new ListItem(""));

            DropDownListStatusCodes.SelectedIndex = 0;


            connection.Close();
            rdr.Close();
        }
    }




    private void ListFieldStatusCodes2()
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string cmdstr = "SELECT DepartureTime FROM DepartureTime";
            SqlCommand cmd = new SqlCommand(cmdstr, connection);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            SqlDataReader rdr;

            rdr = cmd.ExecuteReader();

            DropDownListStatusCodes2.Items.Clear();

            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    DropDownListStatusCodes2.Items.Add(rdr["DepartureTime"].ToString());
                }
            }

            DropDownListStatusCodes2.SelectedIndex = 0;

            connection.Close();
            rdr.Close();
        }
    }

    private void ListFieldStatusCodes3()
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string cmdstr = "SELECT BusType FROM BusType";
            SqlCommand cmd = new SqlCommand(cmdstr, connection);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            SqlDataReader rdr;

            rdr = cmd.ExecuteReader();

            DropDownListStatusCodes3.Items.Clear();

            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    DropDownListStatusCodes3.Items.Add(rdr["BusType"].ToString());
                }
            }

            DropDownListStatusCodes3.SelectedIndex = 0;

            connection.Close();
            rdr.Close();
        }
    }
    private void ListFieldStatusCodes4()
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string cmdstr = "SELECT Fare FROM Fare";
            SqlCommand cmd = new SqlCommand(cmdstr, connection);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            SqlDataReader rdr;

            rdr = cmd.ExecuteReader();

            DropDownListStatusCodes4.Items.Clear();

            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    DropDownListStatusCodes4.Items.Add(rdr["Fare"].ToString());
                }
            }

            DropDownListStatusCodes4.SelectedIndex = 0;

            connection.Close();
            rdr.Close();
        }
    }

    private void ListFieldStatusCodes5()
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string cmdstr = "SELECT BusID FROM Bus WHERE Availability='Available'";
            SqlCommand cmd = new SqlCommand(cmdstr, connection);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            SqlDataReader rdr;

            rdr = cmd.ExecuteReader();

            DropDownListStatusCodes5.Items.Clear();

            if (rdr.HasRows)
            {
                while (rdr.Read())
                {
                    DropDownListStatusCodes5.Items.Add(rdr["BusID"].ToString());
                }
            }

            DropDownListStatusCodes5.SelectedIndex = 0;

            connection.Close();
            rdr.Close();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {


        if (!IsPostBack)
        {
            ListFieldStatusCodes();
            ListFieldStatusCodes2();
            ListFieldStatusCodes3();
            ListFieldStatusCodes4();
            ListFieldStatusCodes5();
            //DropDownListStatusCodes.SelectedValue = "Available";

            lblSuccessInsert.Visible = false;


        }

    }


    protected void btnSave_Click(object sender, EventArgs e)
    {

        try
        {


            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(
                "INSERT INTO Trip (Terminal, DepartureTime, Destination , " +
                "BusType, Fare, BusID) " +

                "VALUES (@Terminal, @DepartureTime, @Destination, @BusType, " +
                "@Fare, @BusID)", connection);


             
                command.Parameters.Add("@Terminal",
                SqlDbType.NVarChar, 50).Value = DropDownListStatusCodes.Text;

                command.Parameters.Add("@DepartureTime",
                 SqlDbType.NVarChar, 50).Value = DropDownListStatusCodes2.Text;

                command.Parameters.Add("@Destination",
                            SqlDbType.NVarChar, 50).Value = DropDownListStatusCodes1.Text;

                command.Parameters.Add("@BusType",
               SqlDbType.NVarChar, 50).Value = DropDownListStatusCodes3.Text;

                command.Parameters.Add("@Fare",
               SqlDbType.NVarChar, 50).Value = DropDownListStatusCodes4.Text;

                command.Parameters.Add("@BusID",
              SqlDbType.Int).Value = DropDownListStatusCodes5.Text;

                connection.Open();
                command.ExecuteNonQuery();

                connection.Close();



                lblSuccessInsert.Visible = true;
            }
        }
        catch (Exception ex)
        {
            string source,
            message;
            source = ex.Source.ToString().Replace(System.Environment.NewLine, " ");
            message = ex.Message.ToString().Replace(System.Environment.NewLine, " ");

            Response.Redirect("/messages/error.aspx?source=" + source + "&message=" + message);
        }

    }


    protected void btnClear_Click(object sender, EventArgs e)
    {
     
     


        lblSuccessInsert.Visible = false;
    }




    protected void btnSelect_Click(object sender, EventArgs e)
    {

    }


    protected void DropDownListStatusCodes_SelectedIndexChanged(object sender, EventArgs e)
    {


        if (DropDownListStatusCodes.SelectedIndex > 0)

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                string cmdstr = "SELECT DestinationID, Destination FROM Destination WHERE TerminalID=" + DropDownListStatusCodes.SelectedValue + " ORDER BY Destination";
                SqlCommand cmd = new SqlCommand(cmdstr, connection);
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                SqlDataReader rdr;
                DataTable dt = new DataTable("tbl");
                rdr = cmd.ExecuteReader();

                DropDownListStatusCodes1.Items.Clear();

                if (rdr.HasRows)
                {
                    while (rdr.Read())
                    {
                        DropDownListStatusCodes1.Items.Add(rdr["Destination"].ToString());
                    }
                }
                DropDownListStatusCodes1.DataSource = dt;
                DropDownListStatusCodes1.DataTextField = "Destination";
                DropDownListStatusCodes1.DataValueField = "DestinationID";
                DropDownListStatusCodes1.DataBind();
                clsUIUtility.FillCombo(DropDownListStatusCodes1, "DestinationID", "Destination", clsUIUtility.ExecuteQuery("SELECT DestinationID, Destination FROM Destination WHERE TerminalID=" + DropDownListStatusCodes.Text + " ORDER BY Destination"), false);




                connection.Close();
                rdr.Close();
            }
        else
        {
            DropDownListStatusCodes1.Items.Clear();
        }
    }
}

Karthik_Mahalingam

какая линия?

Edgar Bots

ListFieldStatusCodes и DropDownListStatusCodes_Selectedindexchanged
в этой части

Karthik_Mahalingam

вы хотите сохранить идентификатор или отображаемый текст?

Karthik_Mahalingam

замените эту функцию следующей

  private void ListFieldStatusCodes()
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
              
                string cmdstr = "SELECT TerminalID, Terminal FROM Terminal";
                SqlCommand cmd = new SqlCommand(cmdstr, connection);
                SqlDataAdapter adp = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable("tbl");
                adp.Fill(dt); 
                DropDownListStatusCodes.DataSource = dt;
                DropDownListStatusCodes.DataTextField = "Terminal";
                DropDownListStatusCodes.DataValueField = "TerminalID";
                DropDownListStatusCodes.DataBind();
                DropDownListStatusCodes.Items.Insert(0, new ListItem(""));
                DropDownListStatusCodes.SelectedIndex = 0;
            }
        }

1 Ответов

Рейтинг:
2

Karthik_Mahalingam

исправительные учреждения

protected void DropDownListStatusCodes_SelectedIndexChanged(object sender, EventArgs e)
   {
       if (DropDownListStatusCodes.SelectedIndex > 0)

           using (SqlConnection connection = new SqlConnection(connectionString))
           {
               connection.Open();
               string cmdstr = "SELECT DestinationID, Destination FROM Destination WHERE TerminalID=@TerminalID ORDER BY Destination";
               SqlCommand cmd = new SqlCommand(cmdstr, connection);
               cmd.Parameters.AddWithValue("@TerminalID",DropDownListStatusCodes.SelectedValue);
               SqlDataAdapter adp = new SqlDataAdapter(cmd);
               DataTable dt = new DataTable("tbl");
               adp.Fill(dt);
               DropDownListStatusCodes1.DataSource = dt;
               DropDownListStatusCodes1.DataTextField = "Destination";
               DropDownListStatusCodes1.DataValueField = "DestinationID";
               DropDownListStatusCodes1.DataBind();

           }
       else
       {
           DropDownListStatusCodes1.Items.Clear();
       }
   }


private void ListFieldStatusCodes()
       {
           using (SqlConnection connection = new SqlConnection(connectionString))
           {

               string cmdstr = "SELECT TerminalID, Terminal FROM Terminal";
               SqlCommand cmd = new SqlCommand(cmdstr, connection);
               SqlDataAdapter adp = new SqlDataAdapter(cmd);
               DataTable dt = new DataTable("tbl");
               adp.Fill(dt);
               DropDownListStatusCodes.DataSource = dt;
               DropDownListStatusCodes.DataTextField = "Terminal";
               DropDownListStatusCodes.DataValueField = "TerminalID";
               DropDownListStatusCodes.DataBind();
               DropDownListStatusCodes.Items.Insert(0, new ListItem(""));
               DropDownListStatusCodes.SelectedIndex = 0;
           }
       }


Примечание:
Форматирование строки sql запроса таково уязвимый к SQL-инъекция[^] атаки
всегда использовать Параметризованные запросы для предотвращения атак SQL-инъекций в SQL Server[^]


Edgar Bots

Я попробовал пересмотренные коды, но это не сработает. Назначение зависит от выбранного значения на терминале. Я попробовал коды и могу выбрать только из терминала, но я не вижу выпадающих данных назначения. Вы не могли бы мне помочь? Спасибо

Karthik_Mahalingam

держите точку останова и посмотрите, какое значение вы получаете в DropDownListStatusCodes.SelectedValue