SqlCommand 字符串到 RowdataBound Header

SqlCommand string to RowdataBound Header

我创建了一个带有字符串“test”的方法来保存我的 SqlCommand 查询。 test = '201813'

public void temp()
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;    
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("SELECT LEFT(CONVERT(VARCHAR(10),GETDATE(),120),4)+ CAST((DATEPART(ISOWK,GETDATE()) - 2) AS NVARCHAR(2))", con);
        con.Open();
        string test = (string)cmd.ExecuteScalar();
        con.Close();
    }
}

现在的问题是如何在接下来的 rowdatabound 事件中重复使用这个字符串?

protected void gwPlanning_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.Cells.Count > 0)
    {
        //Translate header text
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[12].Text = test.ToString();    
        }

    }       
}

我正在尝试使用 e.Row.Cells[12].Text = **test.ToString();

任何人都可以帮助我解决我做错了什么吗?

在您的代码中,字符串变量 testtemp() 的局部变量,如果您想在 gwPlanning_RowDataBound 中使用它,您要么必须创建函数temp 到 return 字符串值,或者您必须将该值保存在全局变量中。

temp() 到 return 一个字符串值。

代码:

public string temp()
{
    string test = string.Empty;
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    using (SqlConnection con = new SqlConnection(CS))
    {
        SqlCommand cmd = new SqlCommand("SELECT LEFT(CONVERT(VARCHAR(10),GETDATE(),120),4)
                            + CAST((DATEPART(ISOWK,GETDATE()) - 2) AS NVARCHAR(2))", con);
        con.Open();
        test = (string)cmd.ExecuteScalar();
        con.Close();
    }
    return test;
}


protected void gwPlanning_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.Cells.Count > 0)
    {
        //Translate header text
        if (e.Row.RowType == DataControlRowType.Header)
        {
            e.Row.Cells[12].Text = temp().ToString();    
        }
    }       
 }