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?

1 Answer 1

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();    
        }
    }       
 }
Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect. You learn something new everyday :) Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.