返回值问题
cs.页面
public string getString()
{
DataSet ds =DBAcess.GetDataSet( "select * from role where r_id in(select r_id from u_r_relation where u_id= ' " + objectid + " ') ", true);
string r_name = " ";
string r_id = " ";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
r_name = ds.Tables[0].Rows[i][ "r_name "].ToString();
r_id = ds.Tables[0].Rows[i][ "r_id "].ToString();
return "document.getElementById( 'Select2 ').add(new Option( ' " + r_name + " ', ' " + r_id + " ',true)); ";
}
}
前台
<select id= "Select2 " name= "dltTarget " multiple >
</select>
<script type= "text/javascript ">
<%=getString()%>
</script>
现在我执行页面的话,就会报
“Test2.getString()”: 并非所有的代码路径都返回值
请问下大家应该如何解决
------解决方案--------------------你的return 语句写到for循环体里去了,for循环可能一次都不执行,所以系统认为可能没有返回值,考虑在循环体外return一个值
------解决方案--------------------public string getString()
{
DataSet ds =DBAcess.GetDataSet( "select * from role where r_id in(select r_id from u_r_relation where u_id= ' " + objectid + " ') ", true);
string r_name = " ";
string r_id = " ";
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
r_name = ds.Tables[0].Rows[i][ "r_name "].ToString();
r_id = ds.Tables[0].Rows[i][ "r_id "].ToString();
}
return "document.getElementById( 'Select2 ').add(new Option( ' " + r_name + " ', ' " + r_id + " ',true)); ";
}
------解决方案--------------------FOR循环可能因为条件不成立而不执行,在FOR循环体外没有return语句,所以报错。
你这个return放在for循环体内,是不恰当的。
------解决方案--------------------public string getString()
{
DataSet ds =DBAcess.GetDataSet( "select * from role where r_id in(select r_id from u_r_relation where u_id= ' " + objectid + " ') ", true);
string r_name = " ";
string r_id = " ";
// 这里,如果ds.Tables[0].Rows.Count==0,也就不会执行ret