【发布时间】:2018-04-09 03:53:41
【问题描述】:
第一道工序:
- 从数据库中获取列 ip_address,subnet
- 我会将列 ip 地址设置为 label1.text 并将子网设置为 label2.text
string connection = "Server=192.168.1.10;Database=xxxxx;User Id=xxxxx;Password=xxxxxx;";
try
{
SqlConnection conn = new SqlConnection(connection);
conn.Open();
var query = "SELECT TOP 1 ip_address,subnet,gateway FROM computer_info WHERE pc_name = HOST_NAME() ORDER BY id DESC";
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
// column ip
string ip_address = dr["ip_address"].ToString();
string sub_net = dr["subnet"].ToString();
string gateway = dr["gateway"].ToString();
label1.Text = ip_address;
label2.Text = sub_net;
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
第二道工序:
-
我想更改我的 IP 地址和子网
注意:ip地址和子网的值来自数据库
public void setIP(string ip_address, string subnet_mask) { ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection objMOC = objMC.GetInstances(); foreach (ManagementObject objMO in objMOC) { if ((bool)objMO["IPEnabled"]) { try { ManagementBaseObject setIP; ManagementBaseObject newIP = objMO.GetMethodParameters("EnableStatic"); newIP["IPAddress"] = new string[] { ip_address }; newIP["SubnetMask"] = new string[] { subnet_mask }; setIP = objMO.InvokeMethod("EnableStatic", newIP, null); } catch (Exception) { throw; } } } }
第三个进程执行
注意:我这里有 2 个示例代码 1 可以工作,而 2 不能工作
private void button1_Click_1(object sender, EventArgs e)
{
setIP(
// if i use this static string value my address is changing.
"192.168.1.5",
"255.255.255.0"
);
///---------------------------------------///////////////////////////////////////
setIP(
//the value inside of label1 , label2 is from database. ??? the question is why there is no result if the value came from the database.
label1.Text,
label2.Text
);
}
我希望你们能帮助我……谢谢。
【问题讨论】: