0

I have created a method with a string "test" that holds my SqlCommand query. 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();
    }
}

The question now is How can I reuse this string in my following rowdatabound event?

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();    
        }

    }       
}

I'm trying to use e.Row.Cells[12].Text = **test.ToString();

Can anyone help me on what im doing wrong?

user9405863
  • 1,506
  • 1
  • 11
  • 16
Nils
  • 516
  • 3
  • 9
  • 33

1 Answers1

1

In your code, the string variable test is a local variable for the temp() and if you want to use that it in gwPlanning_RowDataBound, either you have to make the function temp to return a string value or you have to save the value in a global variable.

temp() to return a string value.

Code:

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();    
        }
    }       
 }
Ullas
  • 11,450
  • 4
  • 33
  • 50