String C#错误:输入字符串的格式不正确
我在VS方面没有什么经验,也不知道我的代码到底出了什么问题:String C#错误:输入字符串的格式不正确,string,c#-4.0,String,C# 4.0,我在VS方面没有什么经验,也不知道我的代码到底出了什么问题: public static DataTable BindStudentsearchList(int FeeDate, int IsArcive) { SqlConnection cn = new SqlConnection(Global.getconnection()); SqlCommand cmdnew = new SqlCommand(); cmdnew.CommandText =
public static DataTable BindStudentsearchList(int FeeDate, int IsArcive)
{
SqlConnection cn = new SqlConnection(Global.getconnection());
SqlCommand cmdnew = new SqlCommand();
cmdnew.CommandText = "SELECT A.Studentid,A.Name,F.FeeDate,F.Fee FROM tbl_Student A inner join tbl_Fee F on A.StudentId= F.fkStudentId where FeeDate= "+ FeeDate +" and A.IsArcive=0";
cmdnew.Connection = cn;
cn.Open();
DataTable dts = new DataTable();
SqlDataAdapter das = new SqlDataAdapter();
das.SelectCommand = cmdnew;
das.Fill(dts);
return dts;
}
}
public void bindUsersearchGrid()
{
DataTable DataTable = new DataTable();
grdFeeDetail.DataSource = BindStudentsearchList(Convert.ToInt32(txtSearch.Text), 0);
}
private void btnDailyFee_Click(object sender, EventArgs e)
{
bindUsersearchGrid();
}
错误是:输入字符串的格式不正确
非常感谢您的帮助
grdFeeDetail.DataSource = BindStudentsearchList(Convert.ToInt32(txtSearch.Text), 0);
如果字符串不能作为整数解析,Convert.ToInt32将引发FormatException。您说txtSearch.Text
将包含日期的字符串表示形式。无法解析为整数的
如果DB列是日期,那么FeeDate应该是日期时间
,您需要使用或而不是Convert.ToInt32
您输入的示例“2014年6月21日”在世界大部分地区看起来都是正确的日期。由于您得到的是FormatException,因此您的计算机可能被设置为不识别“dd/m/yyyy”为有效日期格式的区域性。DateTime.Parse、DateTime.ParseExact和Convert.ToDateTime的重载允许您指定格式或区域性信息
此外,即使FeeDate
是一个整数,不易受到SQL注入的影响,使用参数化查询而不是串接字符串仍然是一个好习惯:
cmdnew.CommandText = "SELECT A.Studentid,A.Name,F.FeeDate,F.Fee FROM tbl_Student A inner join tbl_Fee F on A.StudentId= F.fkStudentId where FeeDate=@feeDate and A.IsArcive=0";
cmdnew.Parameters.Add(new SqlParameter("@feeDate", FeeDate));
抛出错误的是哪一行?我们需要更多的细节来帮助你。您显示的唯一字符串是您的
cmdnew.CommandText
,粗略一看就可以了。使用参数化查询。。。ps Feedate对于整数来说是一个非常糟糕的名字…因为您没有告诉我们,我假设它是Convert.ToInt32(txtSearch.Text)
,因为您在txtSearch
中没有有效的数字。这一行--grdFeeDetail.DataSource=BindStudentsearchList(Convert.ToInt32(txtSearch.Text),0;我想搜索那个在日期提交了费用的学生。那么你认为Convert.ToInt32(“21/6/2014”)
会怎么做?我已根据此更新了我的答案。我尝试了它,但也出现了一个错误,并且我尝试了转换。ToDatetime()则其时间错误为字符串。未将其识别为有效的DateTime。根据此更新了答案。您遇到的问题是将字符串解析为日期。计算机上的CurrentCulture设置可能有问题,但尝试将其转换为整数并不能解决问题。