Reputation: 909
I'm new to Asp.net and have looked around for how to do this, but haven't been able to find it.
I would like to create a detailsview entirely from codebehind. This is because I need certain fields to load based on the user's permissions. Also, I would like the ability to edit the detailsview to be only accessible to certain users. Is there a way to do this?
Upvotes: 1
Views: 2500
Reputation: 342
To complete R.C. answer: In dataBinding method, if datasource is not a DataRowView, you may use:
lblID.Text = DataBinder.Eval(dv.DataItem,"CustomerID").ToString();
It works for me. I found it several times on this forum.
Upvotes: 0
Reputation: 10565
This is a very basic implementatation of DetailsView programmatically. This will get you started.
protected void Page_Load(object sender, EventArgs e)
{
DetailsView dv = new DetailsView();
dv.ID = "MyDv";
dv.DataSource = GetDataSet(); // returns a dataset filled using Select Query
TemplateField tf = new TemplateField();
tf.ItemTemplate = new AddTemplateToDetailsView(ListItemType.Item);
dv.Fields.Add(tf);
dv.DataBind();
placeholder1.Controls.Add(dv);
}
Class file code to add TemlplateField. <asp:TemplateField>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Data;
public class AddTemplateToDetailsView : ITemplate
{
private ListItemType _ListItemType;
public AddTemplateToDetailsView(ListItemType listItemType)
{
_ListItemType = listItemType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
if (_ListItemType == ListItemType.Item)
{
Label lblID = new Label();
lblID.DataBinding += new EventHandler(lblID_DataBinding);
container.Controls.Add(lblID);
}
}
void lblID_DataBinding(object sender, EventArgs e)
{
Label lblID = (Label)sender;
DetailsView container = (DetailsView)lblID.NamingContainer;
lblID.Text = ((DataRowView)container.DataItem)["CustomerID"].ToString();
}
}
In case you also need to add InsertItemTemplate
OR EditItemTemplate
, You can create UserControls for the same and add those in Page_Init()
as below. The UserControl must Inherit ITemplate
.
protected void Page_Init(object sender, EventArgs e)
{
this.DetailsView1.EditItemTemplate = Page.LoadTemplate("UserControlEdit.ascx");
this.DetailsView1.InsertItemTemplate = Page.LoadTemplate("UserControlInsert.ascx");
}
Read MSDN here .
Upvotes: 2