簡體   English   中英

通過循環通過Winform控件以編程方式獲取checkbox.checked值

[英]Get checkbox.checked value programmatically from cycling through winform controls

對於我的winforms程序,我有一個“選項”對話框,當它關閉時,我循環瀏覽所有“對話框”控件名稱(文本框,復選框等)及其值,並將其存儲在數據庫中,以便我可以從中讀取我的程序。 正如您在下面看到的,我可以輕松地從Control組訪問Text屬性,但是沒有屬性可以訪問文本框的Checked值。 在這種情況下,我是否需要先將c轉換為復選框?

conn.Open();
foreach (Control c in grp_InvOther.Controls)
{
    string query = "INSERT INTO tbl_AppOptions (CONTROLNAME, VALUE) VALUES (@control, @value)";
    command = new SQLiteCommand(query, conn);
    command.Parameters.Add(new SQLiteParameter("control",c.Name.ToString()));
    string controlVal = "";
    if (c.GetType() == typeof(TextBox))
        controlVal = c.Text;
    else if (c.GetType() == typeof(CheckBox))
        controlVal = c.Checked; ***no such property exists!!***

    command.Parameters.Add(new SQLiteParameter("value", controlVal));
    command.ExecuteNonQuery();
}
conn.Close();

如果我需要先轉換c ,我該怎么做?

是的,您需要轉換它:

else if (c.GetType() == typeof(CheckBox))
    controlVal = ((CheckBox)c).Checked.ToString(); 

您可以使支票更易於閱讀:

else if (c is CheckBox)
    controlVal = ((CheckBox)c).Checked.ToString(); 

羅伯特的回答很好,但我給你一個更好的答案

TextBox currTB = c as TextBox;
if (currTB != null)
    controlVal = c.Text;
else
{
    CheckBox currCB = c as CheckBox;
    if (currCB != null)
    controlVal = currCB.Checked;
}

您可以投放到位:

controlVal = (CheckBox)c.Checked;

順便說一句:controlVal不必是字符串,布爾值將完成工作並節省內存。

嘗試這個:

controlVal = Convert.ToString(c.Checked);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM