[英]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.