我是C#的新手..
我有写功能来过滤部门。此功能将返回 idDepartment 。
新问题,部门保持值“ System.Windows.Forms.Label,Text:ADMIN ”,这就是为什么我得零。那么我怎么才能只接受“ADMIN”并留到部门?
更新:
public partial class frmEditStaff : Form
{
private string connString;
private string userId, department; //Department parameter coming from here
private string conString = "Datasource";
public frmEditStaff(string strUserID, string strPosition)
{
InitializeComponent();
//Pass value from frmListStaff to userID text box
tbStaffId.Text = strUserID.ToString();
userId = strUserID.ToString();
department = strPosition.ToString();
}
以下代码正常运行,没有任何问题。
public int lookUpDepart()
{
int idDepart=0;
using (SqlConnection openCon = new SqlConnection(conString))
{
string lookUpDepartmenId = "SELECT idDepartment FROM tbl_department WHERE department = '" + department + "';";
openCon.Open();
using (SqlCommand querylookUpDepartmenId = new SqlCommand(lookUpDepartmenId, openCon))
{
SqlDataReader read = querylookUpDepartmenId.ExecuteReader();
while (read.Read())
{
idDepart = int.Parse(read[0].ToString());
break;
}
}
openCon.Close();
return idDepart;
}
}
感谢您的帮助。祝你好日子快乐!
答案 0 :(得分:1)
关于你的问题:部门保持价值" System.Windows.Forms.Label,文字:ADMIN"
您在此次通话中遇到问题 frmEditStaff(strUserID,yourLabel.ToString());
虽然你还没有共享你对这个函数/构造函数的调用,但是看起来你的第二个参数在这个调用中出错了。请勿在此处使用ToString()
。相反,您必须使用.Text
作为
frmEditStaff(strUserID,yourLabel.Text);
这将解决您的问题。我知道这一点,因为程序员通常会犯这样的错误:)
答案 1 :(得分:0)
public int lookUpDepart()
{
int idDepart = 0;
using (SqlConnection con = new SqlConnection(conString))
{
string lookUpDepartmenId = "SELECT idDepartment FROM tbl_department WHERE department = " + department;
con.Open();
using (SqlCommand querylookUpDepartmenId = new SqlCommand(lookUpDepartmenId, openCon))
{
SqlDataReader read = querylookUpDepartmenId.ExecuteReader();
while (read.Read())
{
idDepart = Convert.ToInt32((read[0]).ToString());
break;
}
}
con.Close();
return idDepart;
}
}
尝试上面的代码,我重写了它。它对我有用......
答案 2 :(得分:0)
从单行中选择单个值时,您可以使用ExecuteScalar方法,为您完成所有这些操作,如下所示:
using (SqlCommand querylookUpDepartmenId = new SqlCommand(lookUpDepartmenId, openCon))
{
idDepart = int.Parse(querylookUpDepartmenId.ExecuteScalar());
}
同样,在SQL查询中使用字符串连接是just plain wrong
对于您更新的问题:尝试使用标签的Text属性,即.ToString()方法的内容。
我建议您获取good tutorial book about C# / .net,并按照示例进行操作。