[英]How to convert Dictionary<string, object> to Dictionary<string, string> in c#
[英]How to convert viewstate “object” to dictionary in c#
下面的代码给我一个令人尴尬的问题。
在第一种方法(加载方法)中,我尝试将存储在viewstate中的字典转移到变量“ dict”中。
我收到错误消息“无法将类型“对象”隐式转换为字典”。
我已经厌倦了打字,但没有成功。 我在这里做错了什么?
提前致谢!
PS(之所以要使用viewstate,是因为重新加载页面后,下面列表框中的选择消失了)
public partial class _Default : System.Web.UI.Page
{
Dictionary<string, int> dict = new Dictionary<string, int>();
protected void Page_Load(object sender, EventArgs e)
{
//throws the implicit conversion error
if (ViewState["dict"] != null) {
dict = ViewState["dict"];
//dict = (Dictionary<string, int>)ViewState["dict"];
}
Response.Write("Reload");
foreach (ListItem li in ListBox1.Items) {
if (dict.ContainsKey(li.Value)) {
if (dict[li.Value] == 3) {
li.Attributes.Add("style", "background-color: green;");
Label3Items.Text += "<br>" + li.Text;
}
else if (dict[li.Value] == 2) {
li.Attributes.Add("style", "background-color: blue;");
Label2Items.Text += "<br>" + li.Text;
}
else if (dict[li.Value] == 1) {
li.Attributes.Add("style", "background-color: yellow;");
Label1Items.Text += "<br>" + li.Text;
}
else {
li.Attributes.Add("style", "background-color: red;");
LabelVetoItems.Text += "<br>" + li.Text;
}
}
}
}
protected void updateName(object sender, EventArgs e)
{
Label1.Text = "Welcome "+TextBox1.Text+"!";
}
protected void Button1_Click(object sender, EventArgs e) {
Updater(3);
}
protected void Button2_Click(object sender, EventArgs e) {
Updater(2);
}
protected void Button3_Click(object sender, EventArgs e) {
Updater(1);
}
protected void ButtonVeto_Click(object sender, EventArgs e) {
Updater(0);
}
protected void Updater(int indexer) {
//loops through listitems, color-marks selected items and stores to dictionary
foreach (ListItem li in ListBox1.Items) {
if (li.Selected == true) {
//li.Enabled = false;
if (indexer == 3) {
li.Attributes.Add("style", "background-color: green;");
Label3Items.Text += "<br>" + li.Text;
dict.Add(li.Value, 3);
}
else if (indexer == 2) {
li.Attributes.Add("style", "background-color: blue;");
Label2Items.Text += "<br>" + li.Text;
dict.Add(li.Value, 2);
}
else if (indexer == 1) {
li.Attributes.Add("style", "background-color: yellow;");
Label1Items.Text += "<br>" + li.Text;
dict.Add(li.Value, 1);
}
else{
li.Attributes.Add("style", "background-color: red;");
LabelVetoItems.Text += "<br>" + li.Text;
dict.Add(li.Value, 0);
}
}
}
//stores the dictionary with updates key-pair objects from user selection
ViewState["dict"] = dict;
}
protected void submit_Click(object sender, EventArgs e) {
//unfinished
}
}
好了,我保存了我的项目并重新打开了它,现在错误消失了,该应用程序开始运行了。 显然,语法是正确的,但这是VS的问题。
抱歉,应该仔细检查这不是IDE错误。 我以前从未有过像这样怪异的VS!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.