Tech Tidbits - Ruby, Ruby On Rails, Merb, .Net, Javascript, jQuery, Ajax, CSS...and other random bits and pieces.

Wednesday, August 27, 2008

Dynamic Details Row in GridView


<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>

<script runat="server">

void GridView1_PreRender(object sender, EventArgs e)
{
if (GridView1.SelectedRow != null)
{
Table table = GridView1.SelectedRow.Parent as Table;

if (table != null)
CreateRow(table, GridView1.SelectedIndex);
}
}

void CreateRow(Table table, int index)
{
GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
row.Cells.Add(CreateColumn());
table.Rows.AddAt(index + 2, row);
}

private TableCell CreateColumn()
{
TableCell cell = new TableCell();
cell.ColumnSpan = GridView1.Columns.Count;
cell.Width = Unit.Percentage(100);

DataSourceControl ds = CreateDataSourceControl();

cell.Controls.Add(ds);
cell.Controls.Add(CreateDetailsView(ds));
return cell;
}

private static DetailsView CreateDetailsView(DataSourceControl ds)
{
DetailsView dv = new DetailsView();
dv.AutoGenerateRows = true;
dv.DataSourceID = ds.ID;
return dv;
}

private DataSourceControl CreateDataSourceControl()

{
SqlDataSource ds = new SqlDataSource();
ds.ConnectionString = WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
ds.SelectCommand = "SELECT * FROM [Users] WHERE [UserID] = @UserID";
ds.ID = "SqlDataSource2";

Parameter cp = new Parameter("UserID", TypeCode.String, GridView1.SelectedValue.ToString());
ds.SelectParameters.Add(cp);
return ds;
}

</script>

<html xmlns="http://www.w3.org/1999/xhtml" >

<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>

<body>
<form id="form1" runat="server">
<div>

 <asp:GridView ID="GridView1" Runat="server" DataSourceID="SqlDataSource1" DataKeyNames="UserID"
AutoGenerateColumns="False" OnPreRender="GridView1_PreRender" EnableViewState="False">
<Columns>
<asp:CommandField ShowSelectButton="True">
<asp:BoundField ReadOnly="True" HeaderText="UserID" DataField="UserID" SortExpression="UserID">
<asp:BoundField HeaderText="UserName" DataField="UserName" SortExpression="UserName"></asp:BoundField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" Runat="server" SelectCommand="SELECT [UserID], [UserName] FROM [Users]"
ConnectionString="<%$ ConnectionStrings:MyConnectionString %>">
</asp:SqlDataSource>

</div>
</form>

</body>
</html>

No comments:

About Me

My photo
Developer (Ruby on Rails, iOS), musician/composer, Buddhist, HSP, Vegan, Aspie.

Labels