I'm trying to add data to a literal which place inside a gridview. Currently code look like this
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
var query = DisplayAllData();
Literal info = (Literal)e.Row.FindControl("ltritemInfo");
if(query != null)
{
foreach (var listing in query)
{
var list = DisplayListById(listing.id);
info.Text = "<h3>" + list.title + "</h3>";
info.Text += "<h4>" + list.description + "</h4>";
}
}
}
This will generate an error
Object reference not set to an instance of an object.
If anyone has an idea about this it will be great help
Thanks
Ensure you're only operating on the data rows, and not the header, footer, separator, pager, etc. The enum for this is DataControlRowtype. This is why your info object/reference is null, as it operates on the header first.
Check that the e.Row.RowType is of type DataRow.
For safety, also check that your info is not null.
protected void GvListingRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var query = DisplayAllData();
Literal info = (Literal)e.Row.FindControl("ltritemInfo");
if(query != null && info !=null)
{
foreach (var listing in query)
{
var list = DisplayListById(listing.id);
info.Text = string.Format("<h3>{0}</h3><h4>{1}</h4>",
list.title, list.description);
}
}
}
}
Related
I'm creating dynamically controls, assigning it at the same dynamically names and ID's but when I click over a button "A" and then over the button "B" and then again to the button "A" this throw me an error
Multiple controls with the same ID were found. FindControl requires that controls have unique IDs.
this is my code and how I try to avoid the repeating I
protected void DynamicButton()
{
//BAD TOOLS INTO THE LIST AND SHOW
List.ListUsers listsArea = new List.ListUsers();
List<Data.Area> Area = listsArea.AreaList();
List<Data.Area> ListOfEquiposNoOk = Area.Where(x => x.AREA == "ENG" && x.STANDBY == 1).ToList();
List<Button> BotonesBad = new List<Button>();
var TeamBad = ListOfEquiposNoOk.Select(x => x.TEAM).Distinct().ToList();
foreach (var team in TeamBad)
{
Button newButtonBad = new Button();
if (newButtonBad.ID != newButtonBad.ID)
{
BotonesBad = Bad.Controls.OfType<Button>().ToList();
BotonesBad.Add(newButtonBad);
}
else
{
newButtonBad.CommandName = "Btn" + Convert.ToString(team);
newButtonBad.ID = "BtnB_" + Convert.ToString(team);
newButtonBad.Text = team;
newButtonBad.CommandArgument = "ENG";
newButtonBad.Click += new EventHandler(newButton_Click);
Bad.Controls.Add(newButtonBad);
newButtonBad.Click += new EventHandler(newButton_Click);
newButtonBad.CssClass = "btn-primary outline separate";
}
}
I need the ID's to fire an UpdatePanel
ADDED
public partial class Dashboard : System.Web.UI.Page
{
static bool enableGood = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DynamicButton();
}
else if(enableGood)
{
DynamicButton();
}
}
protected void DButton(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);
enableGood = true;
DynamicButton();
}
Assuming "team" is an object in this line:
newButtonBad.ID = "BtnB_" + Convert.ToString(team);
There could be your problem. ".ToString()" usually returns the type as string. So every button will get the same name (since they are all of type "team").
You could override ToString() in your team object, or use a specific team property (e.g team.ID). You could use the property like this:
newButtonBad.ID = "BtnB_" + team.ID.ToString();
Also as already pointed out in the comments, change your evaluation from
if (newButtonBad.ID != newButtonBad.ID)
to
if (team.ID != newButtonBad.ID)
That should do the trick.
I'm designing a CheckOut page and I want to automatically load the signed in user's information with data from the database using linq. I'm using a method FillPage which I call in PageLoad and so far it looks like this:
void FillPage(int id)
{
using (DatabaseContext db=new DatabaseContext()
{
var query = (from user in db.[tblUser]
where user.ID == id
select user
).First();
if (query != null)
{
txtName.Text = query.Username;
txtEmail.Text = query.Email;
txtAddress.Text = query.PostalAddress;
ddProvice.SelectedValue = query.Province;
lblPassword.Text = query.Password;
lblDate.Text = query.DateRegistered.ToString();
}
}
}
Why does nothing happen when I load the page?
You must insert more of your code .your problem is not clear
May be in your load event of your page you forget to add
If (! IsPostback)
{
}
And may be you have reset your fields
public void MyPage_load( object sender , EventArgs e)
{
//Reset fields
}
This will fix your problem
public void MyPage_load( object sender , EventArgs e)
{
If (! IsPostback)
{
//Reset fields
}
}
Here i am updating the gridview value but the value is not updating..TextBox txtID,TextBox txtName,TextBox txtAge retains the older value only and the value is not getting updated..Can anyone tel me like what am i doing wrong here
Here is my code
protected void gvTemp_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
GridViewRow row = (GridViewRow)gvTemp.Rows[e.RowIndex];
int autoid = Int32.Parse(gvTemp.DataKeys[e.RowIndex].Value.ToString());
int id = Convert.ToInt32(gvTemp.DataKeys[e.RowIndex].Values[0].ToString());
activeTabIndex = Convert.ToInt16(Session["activeTabIndex"]);
TextBox txtID = ((TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtId"));
TextBox txtName = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtName");
TextBox txtAge = (TextBox)gvTemp.Rows[e.RowIndex].FindControl("txtAge");
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["ID"] = txtID.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Name"] = txtName.Text;
dataSetInSession.Tables["Days" + activeTabIndex.ToString()].Rows[e.RowIndex]["Age"] = txtAge.Text;
gvTemp.DataSource = dataSetInSession.Tables["Days" + activeTabIndex.ToString()];
gvTemp.DataBind();
gvTemp.EditIndex = -1;
}
and
private void CreateDataSkeletton(int intTabIndex)
{
dataSetInSession = new DataSet();
Session["intTabIndex"] = intTabIndex;
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (dataSetInSession.Tables["Days" + intTabIndex].Rows.Count > 0)
{
gvTemp.DataSource = dataSetInSession.Tables["Days" + intTabIndex];
gvTemp.DataBind();
}
else
{
gvTemp.DataSource = dataSetInSession.Tables["Days"];
gvTemp.DataBind();
}
temp.Controls.Add(gvTemp);
}
Any suggestion??
EDIT(1):
protected void Page_Init(object sender, EventArgs e)
{
if (!IsPostBack)
{
AddDataTable();
}
dataSetInSession = new DataSet();
if (Session["dataSetInSession"] != null)
{
dataSetInSession = (DataSet)Session["dataSetInSession"];
}
if (Session["dynamicTabIDs"] != null)
{
//if dynamicTabIDs are in session, recreating the Tabs
//that are associated with the Tab IDs
//and adding them to the TabContainer that will contain
//all of the dynamic tabs.
//retrieving the tab IDs from session:
dynamicTabIDs = (List<string>)Session["dynamicTabIDs"];
if (TabContainerContent.ActiveTabIndex == -1)
{
TabContainerContent.ActiveTabIndex = Convert.ToInt16(Session["intTabIndex"]);
}
CreateDataSkeletton(Convert.ToInt16(Session["intTabIndex"]));
//looping through each TabID in session
//and recreating the TabPanel that is associated with that tabID
foreach (string tabID in dynamicTabIDs)
{
//creating a new TabPanel that is associated with the TabID
AjaxControlToolkit.TabPanel tab = new AjaxControlToolkit.TabPanel();
//TabContainerContent.ActiveTabIndex = tab;
//Setting the ID property of the TabPanel
tab.ID = tabID;
//setting the TabPanel's HeaderText
tab.HeaderText = "Days " + (TabContainerContent.Tabs.Count + 1).ToString();
//creating a Label to add to the TabPanel...at this point you'll have to
//create whatever controls are required for the tab...
Label tabContent = new Label();
//Giving the Label an ID
tabContent.ID = "lbl_tab_" + TabContainerContent.Tabs.Count.ToString();
//Setting the Label's text
tabContent.Text = "Tab " + (TabContainerContent.Tabs.Count + 1).ToString();
//Adding the Label to the TabPanel
tab.Controls.Add(tabContent);
//Adding the TabPanel to the TabContainer that contains the dynamic tabs
TabContainerContent.Tabs.Add(tab);
}
}
else
{ //Creating a new list of dynamicTabIDs because one doesn't exist yet in session.
dynamicTabIDs = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Read Page Life Cycle
And you will get, that if you want to bind in code-behind, you should do it in Init Event, other wise there are no events will fire.
It seems to be Page.IsPostback problem.Need to add Page.IsPostback property in your page_load like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Put your code inside that.
}
}
Actually your control is getting new value but when you click for updation then it calls old value from page_load.So try to put Page.IsPostback into your page_load event,Just like i mentioned.
I hope it helps.
I have a DataSource bound to a LookUpEdit. For example I have 2 columns FirstName and LastName and I want to set DisplayMember property to these two columns.
I found that I should subscribe to lookUp_CustomDisplayText() and edit display text property like this:
private void lookUpCompanyPerson_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
{
LookUpEdit edit = sender as LookUpEdit;
if (e.DisplayText != "")
{
e.DisplayText = e.DisplayText + " " + (string)e.Value;
}
}
but I did not understand what e.Value is and I want to display another column for selected row, not the valuemember of selected row.
This is how I bind the datasource to lookupedit:
private void populateComboBoxForCompanyPerson()
{
lookUpCompanyPerson.Properties.ForceInitialize();
bs = new BindingSource(myDataSet, "CompanyPerson");
lookUpCompanyPerson.Properties.DataSource = bs;
lookUpCompanyPerson.Properties.DisplayMember = "CompanyName";
lookUpCompanyPerson.Properties.ValueMember = "PersonID";
this.lookUpCompanyPerson.Properties.Columns.Add(new LookUpColumnInfo("PersonID"));
this.lookUpCompanyPerson.Properties.Columns["PersonID"].Visible = false;
this.lookUpCompanyPerson.Properties.Columns.Add(new LookUpColumnInfo("FirstName"));
this.lookUpCompanyPerson.Properties.Columns.Add(new LookUpColumnInfo("LastName"));
this.lookUpCompanyPerson.Properties.Columns.Add(new LookUpColumnInfo("CompanyName"));
}
And this is what my datasource looks like:
I've changed Ian O'Brien's code a little bit and it works:
private void lookUpCompanyPerson_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
{
RepositoryItemLookUpEdit props;
if (sender is LookUpEdit)
props = (sender as LookUpEdit).Properties;
else
props = sender as RepositoryItemLookUpEdit;
if (props != null && (e.Value is int))
{
DataRowView row = props.GetDataSourceRowByKeyValue(e.Value) as DataRowView;
if (row != null)
{
e.DisplayText = String.Format("{0} {1}", row["FirstName"], row["LastName"]);
}
}
}
From the DevExpress documentation:
e.Value gets or sets editor's current value.
e.DisplayText gets or sets an editor's display text
The lookup editor's value is obtained from the data source field specified by the RepositoryItemLookUpEditBase.ValueMember property. The GetDataSourceRowByKeyValue method searches for the specified value within this field and returns an object representing the first found record.
The GetDataSourceRowByKeyValue method's return value depends upon the type of the underlying data source. If the data source is a System.Data.DataTable or a System.Data.DataView, this method returns a System.Data.DataRowView object. If the data source is a custom list of items, the appropriate list item is returned.
You want to set the e.Value to the value that you want to display in the control.
private void lookUpCompanyPerson_CustomDisplayText(object sender, CustomDisplayTextEventArgs e)
{
RepositoryItemLookUpEdit props
if (sender is LookUpEdit)
props = (sender as LookUpEdit).Properties;
else
props = sender as RepositoryItemLookUpEdit;
if (props != null && (e.Value is int))
{
object row = props.GetDataSourceRowByKeyValue(e.Value);
if (row != null)
{
e.Value = String.Format("{0} {1}", (DataRowView)row["FirstName"], (DataRowView)row["LastName"]);
e.Handled = true;
}
}
}
Finally, here are some useful pages with more documentation:
BaseEdit.CustomDisplayText Event
RepositoryItemLookUpEdit.GetDataSourceRowByKeyValue Method
i have use it, just like this;
cmb_tip.Properties.DataSource = _dt;
cmb_tip.Properties.ValueMember = "Value";
cmb_tip.Properties.DisplayMember = "Type";
cmb_tip.Properties.PopulateColumns();
cmb_tip.Properties.Columns["Value"].Visible = false;
This is how it works with LookupEditControl in Version 15.2.7 and a Class:
private void lookUpEditPatients_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
{
var edit = sender as LookUpEdit;
var props = edit.Properties;
var pat = (Patients4ComboBoxVm) props?.GetDataSourceRowByKeyValue(e.Value);
if (pat != null)
{
e.DisplayText = pat.Nachname + ", " + pat.Vorname + "; " + pat.Geburtsdatum + "; " + pat.Versicherungsnummer;
}
}
i can bind the dropdownlist in the edit item template. The drop down list is having null values.
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
DropDownList drpBuildServers = new DropDownList();
if (grdDevelopment.EditIndex == e.Row.RowIndex)
{
drpBuildServers = (DropDownList)e.Row.Cells[0].FindControl("ddlBuildServers");
}
}
also getting an error
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.
I had problems with find control, in the end I used a little bit of recursion to find the control:
private Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
{
return root;
}
foreach (Control c in root.Controls)
{
Control t = FindControlRecursive(c, id);
if (t != null)
{
return t;
}
}
return null;
}
Then to find your control make this call:
drpBuildServers = (DropDownList) FindControlRecursive(e.Row.Cells[0], "ddlBuildServers");
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpBuildServers;
drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;
if (drpBuildServers != null)
// Write your code here
}
}
try http://www.codeproject.com/KB/webforms/editable_gridview_control.aspx , it could be helpful
Its a solution for me:
protected void grdDevelopment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList drpBuildServers;
drpBuildServers = e.Row.FindControl("ddlBuildServers") as DropDownList;
if (drpBuildServers != null)
// Write your code here
}
}