How to fetch the Item Property/Fields in Sitecore? - c#

I am trying to fetch a field called footer from the Item FooterComponent and want to display.This is the code I have tried but cannot fetch and display.
cs code:
Item footerText=Sitecore.content.Database.GetItem(GUID);
string MyFooter=FooterText["Footer"];
txtFooter.Item = MyFooter;
ascx code:
<sc:fieldrenderer runat="server" id="txtFooter" fieldname="Footer"/>

You should not set a string value of the field to the field renderer. Just set correct item and field name:
Item footerTextItem = Sitecore.content.Database.GetItem(GUID);
txtFooter.Item = footerTextItem;
<sc:fieldrenderer runat="server" id="txtFooter" fieldname="Footer"/>
See more information here: https://sitecoresandbox.com/tag/fieldrenderer/
Also read What's a good way to set the Item or DataSource attribute of a FieldRenderer?

Related

CheckBoxList Value gets overwritten by Text on DataBind ASP.NET web forms

I have a CheckBoxList that I want to populate using a collection of ListItems with Text and Values defined.
var temp = types.Select(x => new ListItem(x["Description"].ToString(), x["TypeCode"].ToString()));
chbox.DataSource = temp;
chbox.DataBind();
The ListItems in temp have the correct Text and Value property values, but after chbox.DataBind(), all of the Value properties are populated with the Text property value.
So if the ListItems in temp look like
Text Value
LetterA A
LetterB B
The ListItems in chbox.Items look like
Text Value
LetterA LetterA
LetterB LetterB
You may want to define
DataTextField="TextField" DataValueField="ValueField"
as shown below:
<asp:CheckBoxList ID="CheckBoxList1" runat="server" DataTextField="TextField" DataValueField="ValueField">
</asp:CheckBoxList>
Please check out DataTextField and DataValueField

how to ignore the first index in required field validation

I am doing required field validation checking, first of all i hard coded "Select an item" to my ddllocation, but when i clicks submit button, system doesn't prompt me a required field message. am I missing out something?
Code Behind
ddlLocation.DataSource = dsResult.Tables[0];
ddlLocation.DataTextField = "location_nm";
ddlLocation.DataValueField = "location_id";
ddlLocation.DataBind();
ddlLocation.Items.Insert(0, "----Select an Item----");
HTML
<asp:RequiredFieldValidator ID="rfvLocation" runat="server"
ControlToValidate="ddlLocation"Display="Dynamic" CssClass="ErrorMsg"
ErrorMessage="Mandatory" InitialValue="1"></asp:RequiredFieldValidator>
you should set the InitialValue by:
InitialValue = "----Select an Item----"
change
ddlLocation.Items.Insert(0, "----Select an Item----");
to
ddlLocation.Items.Insert(0, new ListItem("----Select an Item----", "1"));
because you have given initial value of RequiredFieldValidator as 1
You can give initial value which will not in the data you bind to drop down list
If you insert item without creating list item, the value field of that item will be null value. then you can't give value to initial value field of the RequiredFieldValidator
FIrst you should insert item in list by this way
ddlLocation.Items.Insert(0, new ListItem("-select item-","0" ));
Then you can set inital value in RequiredFieldValidator like this
InitialValue = "0"
0 is preferred because may be 1 can be id of any other location in dropdown .

Dropdownlist data binding inside detailsview in asp.net

I have detailsview that will be used to edit customer records. Inside this detailsview, I have a dropdownlist that shows list of countries.
I have a table called CountryList that will populate list of countries to the above dropdownlist.
User can edit and save data without any issue.
But, assume that customer record has the country selected as "Australia" and if I delete Australia from the CountryList and try to edit the customer inside the details view, I am getting below error.
SelectedValue which is invalid because it does not exist in the list of items
I know the reason because the
SelectedValue='<%# Bind("Country") %>'
and it can't find it in the list.
So my question is, how to overcome this issue ?
After searching the web, I found that I can override the Databind but I am not sure how to do this. Have no idea how to override and can someone please give me sample code ?
Also is there any other solution for this such as validate it before set ?
Thank you.
you can call function before selecting value as follows:
SelectedValue='<%# CheckCountry(Eval("Country"))%>'
in aspx.cs file create function as follows which will check whether country is exist in list or not if it is not there then will show default value as selected
public string CheckCountry(string country)
{
// add your logic to check contry in list
// and return value as per result if it is exist
// return country name else return default value
}
Try checking the existence of the country in your list(dataTable,DataSet etc) before binding ,some thing like
DataTable dtPs=getAvailableCountries();
string countryName = "Australia";
DataRow foundRow = dtPs.Rows.Find(countryName);
if(foundRow != null) {
//You have it ...
bindTheDropdown();
}else{
//You dont have it ...
dontBindTheDropdown();
}

Dropdown List will not populate

I'm not sure how to correct the following problem. I have dropdown list that has a object data source. Then in the code there is a method like this
void InitPageData()
{
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
//rank.Text = mr.rank;
//position.Text = mr.position;
UserName.Text = user.UserName;
...
}
This method populates form fields on the page. What I'm trying to do is to have the rank dropdown list populated from the ods but use this method above to populate the selected item of the rank dropwon list with the line rank.Text = mr.rank. In this example the the line of code that throws the error is commented out otherwise it throws this: "'rank' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value".
I've chaned the code to rank.DataTextFiled = mr.rank and rank.DataValueField = mr.rankid.ToString() but this threw another error: "DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Star'." "Star" is the value of the mr.rank.
Here is what the dropdown list and the ods look like:
<asp:DropDownList runat="server" ID="rank" CssClass="txtfield" DataSourceID="ODCRanks"
DataTextField="Rank" DataValueField="ID" AppendDataBoundItems="True">
<asp:ListItem Text="--- Select a Rank ---" Value="-1" />
<asp:ObjectDataSource ID="ODCRanks" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetRanks"
TypeName="RanksTableAdapters.RankTableAdapter"></asp:ObjectDataSource>
You should try adding data columns to your data tables (with ID and Rank being the column name) so that the data can be binded to control.
The Text property sets it by value.
See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.text.aspx
You seem to have what will be the text associated with the value and you want to set that as the selected item. I guess this mostly because your value collection is bound to something called ID and I figure a rank of Star isn't an ID.
If Star is what will show up as something in DataTextField, use the items collection FindByText method to select it.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemcollection.findbytext.aspx
Example
ListItem li = DropDownList1.Items.FindByText("one");
if (li != null) li.Selected = true;
If Star is indeed an ID, then check that the collection is fully loaded before trying to select anything in it.
try something like
rank.SelectedIndex = rank.Items.IndexOf(rank.Items.FindByText(mr.rank));

Telerik getting selected ID (Get data from Radgrid selected item)

I can get the selected index of the gridview but i want to get the actual data that is inside the grid. I want to select a row in the grid and be able to access the "Client Id" column's actual data value. The grid is working fine and I am able to access the SelectedIndexChanged event. I have then been trying with no luck to find a way to get the information that is displayed in the grid. Any help would be greatly appreciated.
Again, I need to get access to all data that is displayed in the grid form the codebehind.
This is what data keys are for. Just designate the columns you want to access as data keys, like in the example shown below.
<telerik:RadGrid ID="RadGrid1" runat="server" ...>
<MasterTableView DataKeyNames="Column1, Column2, Column3" ...>
...
</MasterTableView>
</telerik>
Once the data keys have been assigned in the markup, you can access them in code-behind by row, or using the SelectedValues property.
if (RadGrid1.SelectedItems.Count > 0)
{
//access a string value
string column1 = RadGrid1.SelectedValues["Column1"].ToString();
//access an integer value
int column2 = (int)RadGrid1.SelectedValues["Column2"];
}
You could do it like this:
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
if (item.selected == true)
string mydata = item["ColumnName"].Text;
}
I recommend you read the documentation on this site http://www.telerik.com/help/aspnet/grid/grdaccessingcellsandrows.html; it will sure help you a lot with Telerik components.
Use DataKeys as James Johnson suggested. You cannot access DataItem property of the GridDataItem in SelectedIndexChanged event. It will be null. According to Telerik documentation "DataItem object is available only when grid binds to data."
When DateItem is available, as in the ItemCreated event, you could do a cast to your original data type MyType:
private void RadGrid_ItemCreated(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
if ((e.Item is GridDataItem)) {
GridDataItem gridDataItem = (GridDataItem)e.Item;
MyType dataItem = (MyType)gridDataItem.DataItem;
}
}

Categories

Resources