using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO.Ports;
namespace Smart_House
{
public partial class WebForm1 : System.Web.UI.Page
{
SerialPort serijska_vrata;
protected void Page_Load(object sender, EventArgs e)
{
/*Inicializacija dropdownList*/
DropDownList1.Items.Add("COM3");
DropDownList1.Items.Add("COM2");
DropDownList1.Items.Add("COM1");
DropDownList1.Items.Add("COM4");
DropDownList1.Items.Add("COM5");
DropDownList1.Items.Add("COM6");
DropDownList1.Items.Add("COM7");
DropDownList1.Items.Add("COM8");
DropDownList1.Items.Add("COM9");
/*Inicializacija Serialport*/
serijska_vrata = new SerialPort();
serijska_vrata.PortName = "COM3";
serijska_vrata.BaudRate = 9600;
if(!IsPostBack)
{
serijska_vrata.Open();
Button3.Text = "\uf011";
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
}
static bool on_off_namizna = false;
protected void Button3_Click(object sender, EventArgs e)
{
if (on_off_namizna == false)
{
serijska_vrata.Write("1");
button_style.Href = "Buttonon.css";
label_style.Href = "labelon.css";
on_off_namizna = true;
}
else if (on_off_namizna == true)
{
serijska_vrata.Write("0");
button_style.Href = "Buttonoff.css";
label_style.Href = "labeloff.css";
on_off_namizna = false;
}
}
}
}
我想编写代码来控制arduino,并在第一次加载页面时打开端口,然后关闭它们手动,我尝试了上面的代码,但端口没有打开,如果我没有if(!IsPostback)那么它有效,但我想第一次打开端口,请帮忙。
答案 0 :(得分:0)
试试这个:
if(!IsPostBack)
{
DropDownList1.Items.Add("COM3");
DropDownList1.Items.Add("COM2");
DropDownList1.Items.Add("COM1");
DropDownList1.Items.Add("COM4");
DropDownList1.Items.Add("COM5");
DropDownList1.Items.Add("COM6");
DropDownList1.Items.Add("COM7");
DropDownList1.Items.Add("COM8");
DropDownList1.Items.Add("COM9");
/*Inicializacija Serialport*/
serijska_vrata = new SerialPort();
serijska_vrata.PortName = "COM3";
serijska_vrata.BaudRate = 9600;
serijska_vrata.Open();
Button3.Text = "\uf011";
}
因为如果将DropDownList ADD方法保留在(!IsPostPack)之外,它将继续推送列表中的项目。