开发者

How to access a string variable outside

 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)


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜