0
 public void Button1_Click(object sender, EventArgs e)
    {


        String a = DropDownList1.SelectedItem.Value;
        String b = DropDownList3.SelectedItem.Value.PadLeft(3, '0');
        String c = TextBox1.Text.PadLeft(5, '0').ToString();
        String d = TextBox2.Text.ToString();
        String digit = a + b + c + d;


        try
        {
            OdbcConnection casetype = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
            casetype.Open();
            //************to get case type     
            string casetypequery = "select casename from casetype where skey=?";



            //************to get case type 
            OdbcCommand casetypecmd = new OdbcCommand(casetypequery, casetype);
            String casetypefromdropdown = DropDownList3.SelectedItem.ToString();
            casetypecmd.Parameters.AddWithValue("?", casetypefromdropdown);
            using (OdbcDataReader casetypeMyReader = casetypecmd.ExecuteReader())
            {
                while (casetypeMyReader.Read())
                {
                    String casename = casetypeMyReader["casename"].ToString();

                }
            }
        }

        catch (Exception ewa)
        {
            Response.Write(ewa);
        }

I am not able to access

String casename = casetypeMyReader["casename"].ToString();

which is inside while loop in my above code. How can i access

'casename'

outside while loop?i want to use it to put the content in HtmlEditor(ajax)

2 Answers 2

1

If you want to access the variable outside the loop you need to declare it outside:

string casename = "some default value";
while (casetypeMyReader.Read())
{
    casename = casetypeMyReader["casename"].ToString();
}
// You can access casename here and it's value will either be the default one
// if the reader returned no rows or the last row being read.
Sign up to request clarification or add additional context in comments.

Comments

1

You could declare an Array or List of strings outside the loop, and save the casename values in that.

List<string> caseNames = new List<string>();
while (casetypeMyReader.Read())
{
    caseNames.Add(casetypeMyReader["casename"].ToString());
}

Now they're all in the array and you can access it wherever.

If there are duplicates, and you need unique values, you can do caseNames.Distinct().ToList() afterwards.

1 Comment

+1 for considering the fact that casename would be set multiple times inside of the while loop and assigning the values to an array.

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.