简体   繁体   中英

ASP.Net C# Use first Row from Reader

conn = new SqlConnection(connectionString);
comm = new SqlCommand("Products.sl_Cartridges", conn);
comm.CommandType = CommandType.StoredProcedure;
comm.Parameters.Add(new SqlParameter("@PrinterID", SqlDbType.Int));
comm.Parameters["@PrinterID"].Value = varPrinterID;conn.Open();

reader = comm.ExecuteReader();
Cartridges.DataSource = reader;
Cartridges.DataBind();
reader.Close();

Is there a way to add some code behind to the above to pick out the values of the first data row of this repeater? It would just save me writing a separate SP which seems a waste. Sorry very new to .Net!

If the result set returned is very small, you can just dump to a DataTable with a SqlDataAdapter and grab the first row. This is very simple but inefficient because it wastes a bunch of unnecessary data flow if the result size is large:

SqlDataAdapter adp = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
adp.Fill(dt);

Cartridges.DataSource = new [] { dt.Rows[0] };
Cartridges.DataBind();

Edit : dt.Rows[0] is not valid because it must be a list. Replace with dt.Rows.Take(1) (if you have LINQ) or new [] { dt.Rows[0] } .

Otherwise, you will need to grab all the values from the first row in the reader and dump them into an object that can be bound to the Cartridges control:

var firstRow = new { Name = reader[0], Value = reader[1], Blah = reader[2], ... };
Cartridges.DataSource = firstRow;
Cartridges.DataBind();

Also, if you use a control like DetailsView instead of Repeater, it will automatically display only one row at a time, and you can filter it to a single row.

Not a very nice solution, but you could add a handler for the repeater's ItemDataBound event and set the Visible property of each item (except the first one) to false:

markup:

<asp:Repeater ID="repeater" runat="server"
  OnItemDataBound="repeater_ItemDataBound">

code-behind:

private bool first = true;
void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (!first) e.Item.Visible = false;
    first = false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM