微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#DropDownList和Session [“”]

如何解决C#DropDownList和Session [“”]

| 大家。 我从下拉列表中选择值有一个小问题。 当用户输入其凭据并选择数据源名称时,它们全部存储在会话中。当用户稍后返回登录页面时,我希望他/她看到最后选择的数据源名称。 它是第一次工作,但是当我尝试更改数据源名称时,它没有改变,但是出现了之前选择的值。您能帮我解决这个问题吗? 谢谢! default.aspx
public partial class _Default : System.Web.UI.Page 
{
    private dbConnection connection = new dbConnection();
    private string[,] errorMessage = 
        { {\"Expired\",\"Unsuccessful\",\"Incorrect\"},{\"Your logon Session Has Expired\",\"Invalid Username or Password\",\"Selected Data Source is not supported within this application\"} };

    protected void Page_Load(object sender,EventArgs e)
    {

        ddlDatabase.DataTextField = \"Value\";
        ddlDatabase.DataValueField = \"Key\"; 
        ddlDatabase.DataSource = dbList.GetDbList();
        ddlDatabase.DataBind();    

        Response.Buffer = true;

        if (Session[\"Error\"] != null)
                ErrorMessage();

        if (Session[\"Datasource\"] != null)
            ddlDatabase.SelectedValue = Session[\"Datasource\"].ToString();
    }

    protected void btnLogin_Click(object sender,EventArgs e)
    {
        string dataSource = ddlDatabase.SelectedValue;
        string userID = txtUserID.Text;
        string password = txtPassword.Text;

        connection = new dbConnection(dataSource,userID,password);

        if (connection.IsValid())
        {
            try
            {
                connection.GetConnection().open();
                Session[\"Username\"] = userID;
                Session[\"Password\"] = password;
                Session[\"Datasource\"] = ddlDatabase.SelectedValue;
                Response.Clear();
                Response.Redirect(\"main.aspx\",false);
            }
            catch (Exception ex)
            {
                lblSessionInfo.Text = ex.Message;
                Session[\"Username\"] = null;
                Session[\"Password\"] = null;
                Session[\"Error\"] = \"Unsuccessful\";
                Response.Clear();
                Response.Redirect(\"default.aspx\");
            }
        }
        else
        {
            Session[\"Username\"] = null;
            Session[\"Password\"] = null;
            Session[\"Datasource\"] = null;
            Session[\"Error\"] = \"Incorrect\";
            Response.Clear();
            Response.Redirect(Request.Url.ToString(),true);
        }
    }

    protected void ErrorMessage()
    {
        int length = errorMessage.Length / 2;

        for (int i = 0; i < length; i++)
            if (Session[\"Error\"].ToString() == errorMessage[0,i])
                lblSessionInfo.Text = errorMessage[1,i];
    }
}
main.aspx(注销)
public partial class main : System.Web.UI.Page
{
    dbConnection connection = new dbConnection();

    protected void Page_Load(object sender,EventArgs e)
    {
        Response.Buffer = true;
        if (Session[\"Username\"] == null)
        {
            Session[\"Error\"] = \"Expired\";
            Response.Clear();
            Response.Redirect(\"default.aspx\");
        }
        else
        {
            Session[\"Error\"] = null;
        }

        Label1.Text = Session[\"Datasource\"].ToString();
    }
    protected void btnlogout_Click(object sender,EventArgs e)
    {
        connection.GetConnection().Close();
        Session[\"Username\"] = null;
        Session[\"Password\"] = null;
        Response.Clear();
        Response.Redirect(Request.Url.ToString(),true); 
    }
}
dbList.cs
public class dbList
{
    public static Dictionary<int,string> GetDbList()
    {
        //List<string> dataSources = new List<string>();
        var dataSources = new Dictionary<int,string>(); 

        RegistryKey reg = (Registry.LocalMachine).OpenSubKey(\"Software\");
        reg = reg.OpenSubKey(\"ODBC\");
        reg = reg.OpenSubKey(\"ODBC.INI\");
        reg = reg.OpenSubKey(\"ODBC Data Sources\");

        if (reg != null)
        {
            string[] items = reg.GetValueNames();
            Array.sort(items);
            int i = 0;
            foreach (string item in items)
            {
                dataSources.Add(i,item);
                i++;
            }
        }

        reg.Close();

        return dataSources;
    }
}
dbConnection.cs
public class dbConnection
{
    private string[] dataSources = { \"name1\",\"name2\",\"name3\" };

    public dbConnection() {}

    public dbConnection(string dataSource,string userID,string password)
    {
        DataSource = dataSource;
        UserID = userID;
        Password = password;
    }

    public string DataSource { get; set; }
    private string UserID { get; set; }
    private string Password { get; set; }

    public OracleConnection GetConnection()
    {
        OracleConnection connection = null;

        string connectionString = 
            @\"Data Source=\"+ DataSource + 
            \";User ID=\" + UserID + 
            \";Password=\" + Password + 
            \";Unicode=True\";

        try
        {
            connection = new OracleConnection(connectionString);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message,\"Error\");
        }

        return connection;
    }

    public bool IsValid()
    {
        int trueCount = 0;

        foreach (string dataSource in dataSources)
            if (DataSource == dataSource) trueCount++;

        if (trueCount > 0) return true;
        else  return false;
    }

}
    

解决方法

        更新:2011年6月13日 您可以尝试在get
GetConnection()
方法中创建
Dictionary
而不是
List<string>
吗?
var dictionary = new Dictionary<int,string>();
dictionary.Add(1,\"Connection1\");
dictionary.Add(2,\"Connection2\");
dictionary.Add(3,\"Connection3\");
dictionary.Add(4,\"Connection4\");

// Binding the dictionary to the DropDownList:
dropDown.DataTextField = \"Value\";
dropDown.DataValueField = \"Key\";
dropDown.DataSource = dictionary;  //Dictionary<int,string>
dropDown.DataBind();
您需要先绑定\'ddlDatabase \',然后设置SelectedValue。否则,将在yourDropdown列表中仅创建1个项目(具有SelectedValue),并且除该项目外,您没有其他项目可供选择。
//Code to databind ddlDatabase
BindDatabaseDropdown();
if (Session[\"Datasource\"] != null)
        ddlDatabase.SelectedValue = Session[\"Datasource\"].ToString();
    ,        难道不是仅仅因为代码的那一部分吗?
protected void Page_Load(object sender,EventArgs e)
{
    ddlDatabase.DataSource = dbList.GetDbList();
    ddlDatabase.DataBind();

    Response.Buffer = true;

    if (Session[\"Error\"] != null)
            ErrorMessage();

    if (Session[\"Datasource\"] != null)
        ddlDatabase.SelectedValue = Session[\"Datasource\"].ToString();
}
ddlDatabase.SelectedValue = Session[\"Datasource\"].ToString();
应仅在首页加载(
if(!isPostBack)
)时调用。现在,在调用Click_handler之前,下拉列表中的所选值将始终(始终)从会话中获取。因此,在那部分中:
Session[\"Password\"] = password;
Session[\"Datasource\"] = ddlDatabase.SelectedValue;
Response.Clear();
ddlDatabase.SelectedValue
不再是用户选择的值...     ,        找到解决方案。这比我想的要简单得多。 我没有使用
ddlDatabase.DataSource
,而是使用了
ddlDatabase.Items.Add();
并加上了
Session[\"Datasource\"] = null;
。以下是代码: default.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OracleClient;
using System.Windows.Forms;

public partial class _Default : System.Web.UI.Page 
{
    private db connection = new db();
    private string[,] errorMessage = 
        { {\"Expired\",\"Unsuccessful\",\"Incorrect\"},{\"Your Logon Session Has Expired\",\"Invalid Username or Password\",\"Selected Data Source is not supported within this application\"} };

    protected void Page_Load(object sender,EventArgs e)
    {
        Response.Buffer = true;

        foreach (string name in connection.GetDbList())
            ddlDatabase.Items.Add(name);

        if (Session[\"Error\"] != null)
                ErrorMessage();

        if (Session[\"Datasource\"] != null)
        {
            ddlDatabase.SelectedValue = Session[\"Datasource\"].ToString();
            Session[\"Datasource\"] = null;
        }

    }

    protected void btnLogin_Click(object sender,EventArgs e)
    {
        string dataSource = ddlDatabase.SelectedValue.ToString();
        string userID = txtUserID.Text;
        string password = txtPassword.Text;

        connection = new db(dataSource,userID,password);

        if (connection.IsValid())
        {
            try
            {
                connection.GetConnection().Open();
                Session[\"Username\"] = userID;
                Session[\"Password\"] = password;
                Session[\"Datasource\"] = ddlDatabase.SelectedValue;
                Response.Clear();
                Response.Redirect(\"main.aspx\",false);
            }
            catch (Exception ex)
            {
                lblSessionInfo.Text = ex.Message;
                Session[\"Username\"] = null;
                Session[\"Password\"] = null;
                Session[\"Datasource\"] = ddlDatabase.SelectedValue;
                Session[\"Error\"] = \"Unsuccessful\";
                Response.Clear();
                Response.Redirect(\"default.aspx\");
            }
        }
        else
        {
            Session[\"Username\"] = null;
            Session[\"Password\"] = null;
            Session[\"Datasource\"] = null;
            Session[\"Error\"] = \"Incorrect\";
            Response.Clear();
            Response.Redirect(Request.Url.ToString(),true);
        }
    }

    protected void ErrorMessage()
    {
        int length = errorMessage.Length / 2;

        for (int i = 0; i < length; i++)
            if (Session[\"Error\"].ToString() == errorMessage[0,i])
                lblSessionInfo.Text = errorMessage[1,i];
    }
}
db.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.OracleClient;
using System.Windows.Forms;
using Microsoft.Win32;

public class db
{
    private string[] dataSources = { \"ValidNames\" };

    public db() {}

    public db(string dataSource,string userID,string password)
    {
        DataSource = dataSource;
        UserID = userID;
        Password = password;
    }

    private string DataSource { get; set; }
    private string UserID { get; set; }
    private string Password { get; set; }

    public OracleConnection GetConnection()
    {
        OracleConnection connection = null;

        string connectionString = 
            @\"Data Source=\"+ DataSource + 
            \";User ID=\" + UserID + 
            \";Password=\" + Password + 
            \";Unicode=True\";

        try
        {
            connection = new OracleConnection(connectionString);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message,\"Error\");
        }

        return connection;
    }

    public List<string> GetDbList()
    {
        List<string> dataSources = new List<string>();

        RegistryKey reg = (Registry.LocalMachine).OpenSubKey(\"Software\");
        reg = reg.OpenSubKey(\"ODBC\");
        reg = reg.OpenSubKey(\"ODBC.INI\");
        reg = reg.OpenSubKey(\"ODBC Data Sources\");

        if (reg != null)
        {
            string[] items = reg.GetValueNames();
            Array.Sort(items);
            foreach (string item in items)
                dataSources.Add(item);
        }

        reg.Close();

        return dataSources;
    }

    public bool IsValid()
    {
        int trueCount = 0;

        foreach (string dataSource in dataSources)
            if (DataSource == dataSource) trueCount++;

        if (trueCount > 0) return true;
        else  return false;
    }
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。