我希望第三个gridview列值依赖于第一列值。我的代码如下:
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow item = e.Row;
string selectSQL = " SELECT fail,COUNT(*) AS 'Count' FROM Table WHERE Id =" + item.Cells[0].Text;
SqlConnection con = new SqlConnection(connectionstring.ToString());
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{ con.Open();
reader = cmd.ExecuteReader();
reader.Read();
if (reader["Count"].Equals("0"))
item.Cells[3].Text = "0";
else
item.Cells[3].Text = reader["Count"].ToString();
reader.Close();
}
catch (Exception err)
{ }
finally
{
con.Close();
}
}
}
编辑:
GridViewRow item = e.Row;
int myvar;
Int32.TryParse(item.Cells[0].Text, out myvar);
string selectSQL = " SELECT COUNT(*) AS 'Count' FROM Table WHERE Id=@myvar group by Id";
我可以这样做吗?我的代码中没有反映任何变化。
我试过调试......控制进入了阻止区域..无法理解我哪里出错了
答案 0 :(得分:0)
您正在RowDataBound
内调用数据库。假设您有数千行,数据库将被调用数千次。
SQL injection
。要解决这些问题,首先您必须得到COUNTS
'对于所有Ids
并将其存储在局部变量中,例如一个词典。然后在RowDataBound
期间,您可以使用局部变量中的数据。
上面的场景我用一些样本数据进行了模拟。
这是我在Page
级别声明的本地变量,
private Dictionary<int, int> dictionaryIds = new Dictionary<int, int>();
这是我的Page_Load方法,
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
这是我的BindData
方法,
private void BindData()
{
DataSet ds = new DataSet();
using (SqlConnection connection = new SqlConnection(connectionstring.ToString()))
{
using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Table", connection))
{
adapter.Fill(ds);
}
}
using (SqlConnection connection = new SqlConnection(connectionstring.ToString()))
{
using (SqlCommand command = new SqlCommand("SELECT COUNT(*) AS 'Count' FROM Table", connection))
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
dictionaryIds.Add(Convert.ToInt32(reader["Id"].ToString()), Convert.ToInt32(reader["Count"].ToString()));
}
connection.Close();
}
}
GridView2.DataSource = ds;
GridView2.DataBind();
}
这是我的RowDataBound
方法,
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);
if (dictionaryIds.ContainsKey(myvar))
item.Cells[3].Text = dictionaryIds[myvar].ToString();
}
}
还有一个建议是,您必须将数据拉入数据访问层。
希望这有帮助。