asp.net C#根据传递的querystring从sql中检索数据

时间:2012-05-15 20:12:06

标签: c# asp.net query-string datareader

假设cardDetailsID为5。

查看数据库cardDetails表中的记录号5,可以看到其他字段包括“bgcolour”和“borderstyle”。因此,对于这个特定记录,我有cardDetailsID = 5,bgcolour = blue,bordersytle = solid。

我希望能够从cardDetailsID获得bgcolour和borderyle设置(蓝色和实体)。

这是到目前为止的代码。查询字符串中的值正在工作(正在传递数字“5”)但现在我如何获得该行的其余设置?

    cardDetailsIDrv.Text = Request.QueryString["cardDetailsID"];
    cardDetailsIDrv.Visible = false;

    //create Connection
    SqlConnection myConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnString"]);


    //create Command
    SqlCommand getCardDetailsCMD = new SqlCommand("SELECT * FROM cardDetails WHERE cardDetailsID =" + Convert.ToInt32(cardDetailsIDrv.Text), myConnection);
    myConnection.Open();

    //create datareader
    SqlDataReader myReader = getCardDetailsCMD.ExecuteReader();

    //code works properly up till here


    try
    {
        //Using DataReader to retrieve info from the database and display it on the panel

        while (myReader.Read())
        { 
           //I'm guessing here is where I'm messing things up
           pnlCardps.BackColor = Color.FromName(myReader["bgcolour"].ToString());
           pnlCardps.BorderStyle = (BorderStyle)Enum.Parse(typeof(BorderStyle), myReader["borderstyle"].ToString());

        }
    }

    finally
    {
        if (myReader != null)
        {
            myReader.Close();
        }

        if (myConnection != null)
        {
            myConnection.Close();
        }
    }

问题已解决!! 我所要做的就是将while循环中的代码调整为:

string bgColour = myReader["bgColour"].ToString();
pnlCardrv.BackColor = Color.FromName(bgColour);

string borderColour = myReader["borderColour"].ToString();
pnlCardrv.BorderColor = Color.FromName(borderColour);

2 个答案:

答案 0 :(得分:1)

首先,您必须获取通过查询字符串传递的detailsID,然后执行查询。

int id;
if(int.TryParse(Request.QueryString["detailsID"],out id))
{

string sql= string.Format("select .. from .. where id={0}",id);// using SqlParameter is much better and secure
// and execute your query and fetch the data reader
while(reader.Read())
{
 // bla bla bla
}
}

答案 1 :(得分:0)

Request.QueryString["detailsID"]将获取查询字符串变量的值。

if (Request.QueryString("detailsID") == null || Request.QueryString("detailsID").Length <= 0 || !int.TryParse(Request.QueryString("detailsID"), out detailsID) || MessageThreadID <= 0)
{
    //This is my standard exception, but you can handle it how you want.
    throw new Exception("Error: unable to load detailsID.  Request.QueryString.count: " + Request.QueryString.Count + " Request.QueryString(\"detailsID\"): " + Request.QueryString("detailsID"));
}