我是C#的初学者,试图制作一个软件,我正处于我必须选择座位(按钮)并将其名称添加到数据库的阶段。以下是目前的代码:
static int i;
int m = 0;// m is the maximum no of seats that can be selected.
public void seatSelector(Button btn) //Function To Change Seat Colour on Click
{
if (i < m && btn.BackColor == Color.Transparent)
{
btn.BackColor = Color.Green;
i++;
}
else if (i <= m && btn.BackColor == Color.Green)
{
btn.BackColor = Color.Transparent;
i--;
}
}
//Lets assume I have total 4 seats(designed as buttons)
private void Seat1A_Click(object sender, EventArgs e)
{
seatSelector(Seat1A);
}
private void Seat1B_Click(object sender, EventArgs e)
{
seatSelector(Seat1B);
}
private void Seat1C_Click(object sender, EventArgs e)
{
seatSelector(Seat1C);
}
private void Seat2D_Click(object sender, EventArgs e)
{
seatSelector(Seat2D);
}
我的问题是,如何提取颜色为绿色的座位(按钮)名称。谢谢
答案 0 :(得分:0)
您可以通过多种方式完成您的目标。
我的一个建议是循环浏览按钮控件并查看已点击的按钮。
//Loop through all controls
Foreach (Button s in Page.Controls.OfType<Button>())
{
//Check button color
IF (s.BackColor = Color.Green) Then
{
//This Button is highlighted
//do stuff;
}
}
答案 1 :(得分:0)
或者你可以做到
// in constructor
Seat1A.Click += seatSelector;
Seat1B.Click += seatSelector;
Seat1C.Click += seatSelector;
// etc.
//. . . . . .
// !!! - What you need here is 3 states: unavailable, selected, unselected
// In the beginning you should fill unavailable
private List<string> _unavailable = new ... //(fill this on form open from db)
// paint unavailable in [lets say] blue
private void PaintUnavailable()
{
foreach (Control c in surface.Controls)
{
if (c.GetType() == typeof(Button) && _unavailable.Contains(c.Text))
{
c.BackColor = Color.Blue; // or ((Button)c).BackColor = Color.Blue
}
}
}
private List<string> _selected = new ...
private void SeatSelector(object sender, EventArgs e)
{
var btn = (Button)sender;
if (!_unavailable.Contains(btn.Text))
{
if (btn.BackColor == Color.Transparent)
{
btn.BackColor = Color.Green;
_selected.Add(btn.Text);
}
else if (BackColor == Color.Green)
{
btn.BackColor = Color.Transparent;
_selected.Remove(btn.Text);
}
}
}
然后你可以使用“selected”来写入db。这只是一个例子,通常需要发生的简单样本。 String/button.text
不是最好的方法。您可以让每个按钮在Tag
属性等中具有特定对象