2 回答

TA貢獻(xiàn)1783條經(jīng)驗(yàn) 獲得超4個(gè)贊
正如 Rufus 所說,我會(huì)使用 RadioButtons,而不是 CheckBoxes。將 RadioButtons 的 Tag 屬性設(shè)置為您想要與它們關(guān)聯(lián)的值,然后使用這樣的函數(shù)來獲取選中項(xiàng)的值。只需將 GroupBox 傳遞給函數(shù)并取回選中的 RadioButton 的值。
private int GetGroupBoxValue(GroupBox gb)
{
int nReturn = 0;
foreach (Control ctl in gb.Controls)
{
if (ctl.GetType() == typeof(RadioButton))
{
if (((RadioButton)ctl).Checked)
{
nReturn = Convert.ToInt32(ctl.Tag);
break;
}
}
}
return nReturn;
}
現(xiàn)在您所要做的就是使用 Rufus 提供的優(yōu)秀代碼來檢查rentDuration TextBox 中的整數(shù),您就大功告成了。

TA貢獻(xiàn)1871條經(jīng)驗(yàn) 獲得超8個(gè)贊
控件的類型與創(chuàng)建公式幾乎沒有關(guān)系。要?jiǎng)?chuàng)建公式,您需要知道所有可能的輸入以及如何組合它們以產(chǎn)生輸出。這可以在一個(gè)方法中完成,例如:
private int GetTotalValue(int vehiclePrice, int driverPrice, int rentDuration)
{
// This is where your formula would go
return (vehiclePrice + driverPrice) * rentDuration;
}
訣竅是將表單控件的狀態(tài)轉(zhuǎn)換為可以插入到方法中的值。執(zhí)行此操作的一種方法(不一定是最好的方法,但在您開始時(shí)可能最容易理解)是檢查每個(gè)控件的值并在Click事件中為您的Submit按鈕設(shè)置適當(dāng)?shù)闹怠?/p>
對于租期,我們可以使用該int.TryParse方法,該方法接受一個(gè)字符串和一個(gè)“out”int 參數(shù),如果字符串是有效整數(shù)則返回真,否則返回假。當(dāng)它退出時(shí),如果轉(zhuǎn)換成功,out 參數(shù)將包含 int 值。
對于其他控件,我們可以使用簡單的if / else if語句來確定檢查了哪個(gè)控件,然后相應(yīng)地設(shè)置我們的值。在這個(gè)例子中,我們在 click 事件中使用臨時(shí)變量來將每個(gè)參數(shù)的值存儲(chǔ)到方法中。如果沒有選中任何必需的控件,我們可以向用戶顯示一條消息并等待他們完成填寫表單。
在這個(gè)例子中,我使用了單選按鈕(并使用了opt前綴,這是很久以前的命名約定,我不確定是否仍然存在——它們曾經(jīng)被稱為選項(xiàng)按鈕):
private void btnSubmit_Click(object sender, EventArgs e)
{
// Validate that rent textbox contains a number
int rentDuration;
if (!int.TryParse(txtRentDuration.Text, out rentDuration))
{
MessageBox.Show("Please enter a valid number for rent duration");
return;
}
// Determine vehicle price based on which option was selected
int vehiclePrice;
if (optToyotaPrado.Checked) vehiclePrice = 50000;
else if (optRollsRoyce.Checked) vehiclePrice = 250000;
else if (optSuzikiWagonR.Checked) vehiclePrice = 2500;
else if (optToyotaCorolla.Checked) vehiclePrice = 10000;
else
{
MessageBox.Show("Please select a vehicle");
return;
}
// Determine driver price
int driverPrice;
if (optWithDriver.Checked) driverPrice = 1500;
else if (optWithoutDriver.Checked) driverPrice = 0;
else
{
MessageBox.Show("Please select a driver option");
return;
}
// Finally set the text to the return value of our original method,
// passing in the appropriate values based on the user's selections
txtTotalValue.Text = GetTotalValue(vehiclePrice, driverPrice, rentDuration).ToString();
}
- 2 回答
- 0 關(guān)注
- 179 瀏覽
添加回答
舉報(bào)