开发者

SQL select query in asp.net

Can anyone tell me how to get the value from SELECT query from a table

protected void Button_Click(object sender, EventArgs e)
{
   string select_qry = "SELECT ID, USER, FILE, DATE, LASTUSED from FILE_INFO where USER = '" + user + "'"; // ID is primary key
   SqlCommand cmd = new SqlCommand(select_qry);
   GridView1.DataSource = GetData(cmd);
   GridView1.DataBind();
}

private DataTable GetData(SqlCommand cmd)
{
   DataTable dt = new DataT开发者_JS百科able();
   SqlDataAdapter sda = new SqlDataAdapter();
   cmd.CommandType = CommandType.Text;
   cmd.Connection = conn1;
   conn1.Open();
   sda.SelectCommand = cmd;
   sda.Fill(dt);
   return dt;
}  

I have different USERS I want to get ID of user if user is different say 'Sheena' has ID value from 1-10 but if user is 'Sara' and she is having ID from 11-20 so I want to get specially ID of particular user how do I get ID from select query can any one know then please help me out :)


if the ID will always be first in the select statement you can call this:

VB.NET

var dt = GetData(cmd);
dt.Rows.Item(0).Item("ID")

C#.NET

var dt = GetData(cmd);
dt.Rows[0]["ID"];


I am not getting you quite well. but

Sample data

DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("userName", typeof(string));

dt.Rows.Add(1, "Sheena");
dt.Rows.Add(2, "Meena");
dt.Rows.Add(2, "Teena");

To get id of first row.

if (dt.Rows.Count > 0)
{
    // return id in first row.
    int id = (int)dt.Rows[0]["id"];
}

DataTable Select method

if (dt.Rows.Count > 0)
{
    DataRow[] dr = dt.Select("userName = 'Meena'");

    if (dr.Length > 0)
    {
            int id2 = (int)dr[0]["id"];
    }

}

There are other methods too but these are quickly I can write.


I think you could do that in your query like

Select case id >= 11 and id <= 20 then 'specially id' end as ID ......

Because 'user' is a parameter so you can know the id range when you creating the query.

So that , there is no need any logic in your source code , just fetch data as @Mark said..

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜