我有一个gridview,其值为列
<asp:HyperLinkField DataNavigateUrlFields="runId" DataTextField="PercentAnalysed" ControlStyle-CssClass="hlink" HeaderText="% ANALYSED" ItemStyle-Width="6%" DataNavigateUrlFormatString="runanalysis.aspx?runId={0}" ItemStyle-Font-Underline="true"/>
由以下代码决定。
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow item = e.Row;
//int myvar;
//Int32.TryParse(item.Cells[0].Text, out myvar);
SqlConnection con = new SqlConnection(connectionstring.ToString());
string selectSQL = " SELECT COUNT(*) AS 'Count' FROM Analysed WHERE runId =@myvar group by runId";
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("@myvar", item.Cells[0].Text);
SqlDataReader reader;
try
{ con.Open();
reader = cmd.ExecuteReader();
reader.Read();
if (item.Cells[8].Text.Equals("0"))
item.Cells[13].Text = "0";
else
{
if (reader["Count"].ToString().Equals("0"))
item.Cells[13].Text = "0";
else
item.Cells[13].Text = reader["Count"].ToString();
reader.Close();
}
}
finally
{
con.Close();
}
}
}
我试过调试它,它给出了这个例外。
除了另外一个例外,我还试图在没有值的情况下读取值。
我单独执行了查询,结果很好但是在某些情况下没有数据存在。所以我插入了这张支票:
if(reader [“Count”]。ToString()。Equals(“”))
但仍然是同样的例外。
有什么想法吗?
另外,我只是尝试了一些虚拟值。该列获得了该值,但它不再是超链接非常奇怪。
答案 0 :(得分:0)
if (reader["Count"].ToString().Equals(""))
也会尝试读取数据。因此,在尝试阅读之前,您必须先检查"reader.HasRows()"
。
可能不是强制性的,但我认为你应该考虑我正在做的以下评论。
代码审核:)
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow item = e.Row;
// Consider this condition here. No need to execute connection and command if u hard coding the value
if (item.Cells[8].Text.Equals("0"))
{
item.Cells[13].Text = "0";
return;
}
// You should always try to do this thing in using?
//using (var sqlConnection = new SqlConnection(connectionstring)
SqlConnection con = new SqlConnection(connectionstring.ToString());
string selectSQL = " SELECT COUNT(*) AS 'Count' FROM Analysed WHERE runId =@myvar group by runId";
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("@myvar", item.Cells[0].Text);
SqlDataReader reader;
try
{ con.Open();
// What about using command behaviour here?? e.g., command.ExecuteReader(CommandBehavior.CloseConnection)
reader = cmd.ExecuteReader();
if(reader.HasRows())
{
reader.Read();
//if (item.Cells[8].Text.Equals("0")) // this check should go as first thing in method
//item.Cells[13].Text = "0";
//else
//{
if (reader["Count"].ToString().Equals("0"))
item.Cells[13].Text = "0";
else
item.Cells[13].Text = reader["Count"].ToString();
reader.Close();
//}
}
}
finally
{
con.Close();
}