I have a drop down list that comes from a sqldatasource that is presented in alphabetical order. Because of this, the lists index numbers do not line up at all with the primary keys within the SQL table. I need to be able to set the drop down list's selection on page load based on primary key information I have.
<asp:DropDownList ID="catagoryDropDown" runat="server" DataSourceID="SqlDataSource3"
DataTextField="Catagory" DataValueField="PK_SupportCatagory" CssClass="dropDownList">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$
ConnectionStrings:ApplicationServices %>"
SelectCommand="SELECT [PK_SupportCatagory], [Catagory] FROM [SupportCatagory] ORDER BY CASE
WHEN [PK_SupportCatagory] = 1 THEN 1 ELSE 2 END, [Catagory]">
</asp:SqlDataSource>
My thought is to get the string by querying the database using that to set the drop down list appropriately.
catagoryDropDown.SelectedValue = "Sick Leave";
The above does not work. How would I accomplish this? Is there a better way to do this?
Garrison Neely's answer did not quite work but it got me on the right track. This ultimatly worked:
int i = 0;
foreach (var item in catagoryDropDown.Items)
{
if (item.ToString().Equals("Sick Leave"))
{
catagoryDropDown.SelectedIndex = i;
break;
}
i++;
}
var selectedIndex = -1;
for(int i = 0; i < catagoryDropDown.Items.Count; i++)
{
if(catagoryDropDown.Items[i].Text.ToLower() == "sick leave")
{
selectedIndex = i;
break;
}
}
if(selectedIndex > -1)
{
catagoryDropDown.SelectedIndex = selectedIndex;
}
Added the .ToLower() because it makes things easier when strings don't have case worries.
Try this:
catagoryDropDown.SelectedValue = catagoryDropDown.Items.FindByText("Sick Leave").Value;
Try this One, I am pretty sure it will work:
ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByText(Convert.ToString(Any Value)));
Make sure the value exist in the datasource (to which the ddl is bound) before.
Related
I have the following code behind:
List<Articles> articles = (from em in db.Articles orderby em.ReceivedDate descending select em).ToList();
gvArticles.DataSource = articles;
gvArticles.DataBind();
Where gvArticles is a GridView. The following is the asp code within that grid:
<p style='font-weight:bold;font-size:17px;color:black;'>
<asp:Label ID="lblDate" runat="server" Text='<%#Eval("datePrinted").ToString() %>'></asp:Label>
</p>
<asp:Label ID="lblBody" runat="server" Text= '<%#Eval("Content")%>'></asp:Label>
... that will clearly show from the DB the fields 'datePrinted' and 'Content'
Is there any way that I can show other value in 'datePrinted' based on a condition? For example, if 'datePrinted' is before 1/1/1990 then put "N/A" instead of the field 'datePrinted' itself?
Or a bit more complex, put "-" if the day is the same as the previous record (time can be different, just day/month/year is the same)?
Of course I could calculate all of that and store it in the DB, so I will pull other fields from the DB, but that sounds extremely inefficient, for any future condition create a new field in the DB. So are there any other ways to achieve the same results?
Ideally a condition, formula, or function that translates values from the DB before binding them to the grid is the most desirable solution.
Any idea?
Create a method in your code behind. Call that method parsing your value instead of using eval.
E.g
public static string ConvertDate(DateTime date)
{
if (date < new DateTime(1990, 1,1) )
{
return "N/A";
}
else
{
return date.ToString("dd/MM/yyyy");
}
}
Place this method where you placed your Eval("datePrinted").
<asp:Label ID="lblDate" runat="server" Text='<%# ConvertDate(Convert.ToDateTime(Eval("datePrinted")) ) %>'></asp:Label>
After days trying to figure out what to do, I found one answer just after posting this question. Basically I realized that you can process the List before assign it to the binding. So my second sample, I did this after loading the list and before assign it to the grid datasource:
string prevDate = "";
foreach(Article myArticle in articles) {
if (((DateTime)myArticle.ReceivedDate).ToShortDateString() != prevDate) {
prevDate = ((DateTime)myMail.ReceivedDate).ToShortDateString();
myArticle.ReceivedDate = prevDate;
}
else myArticle.ReceivedDate = "-";
}
Now, I am not a LINQ expert, if anyone can do the same code in the line where the DB is loaded in the List, I would appreciate it.
On default.aspx I have the following hidden fields:
<asp:HiddenField runat="server" ID="icon1" />
<asp:HiddenField runat="server" ID="icon2" />
<asp:HiddenField runat="server" ID="icon3" />
As you can see, the name of the field is the same each time but increments by 1 up to 3.
In my code behind I have been doing this (if statements and other code removed for brevity - this is the meat of it):
icon1.Value = "Bonus1";
icon2.Value = "Bonus2";
icon3.Value = "Bonus3";
Must I assign the iconX.Value individually every time like that? Can I do it all in one shot in a loop (also with everything else removed for brevity)?
for (int i = 1; i <=3; i++)
{
icon(i).Value = "Bonus" + i.ToString();
}
Everything I have read leads me to believe this is not possible in C#. Let's pretend I have 50 iconX.Value = whatever to assign. A loop makes the most logical sense. Possible?
A loop makes the most logical sense. Possible?
Yes. Use the FindControl method of the page to look up a control by its ID:
for (int i = 1; i <= 3; i++)
{
HiddenField field = (HiddenField)this.FindControl("icon" + i);
field.Value = "Bonus" + i.ToString();
}
Note: Because the return type of FindControl is Control, you must cast the result in order to access properties specific to HiddenField.
You have to create a asp:panel in the HTML section.
Then, in the c# code, make a loop and create elements like you describe.
When the element is fully configured, add it to the panel.
.ASPX file
<asp:Panel ID="panel_controls" runat="server"> </asp:Panel>
C# code
for (int i = 1; i <= 3; i++) {
HiddenField myField = new HiddenField();
myField.ID = "icon" + i;
myField.Value = "Bonus" + i;
panel_controls.Controls.Add(myField);
}
Im trying to bind my drop down list, i think is beacuse my asp code on the front end is not bound somehow
aspx
<asp:Label ID="Label2" runat="server" />
<asp:DropDownList Width="150px" ID="ddLocation" runat="server"
AppendDataBoundItems="True"
DataTextField="Name"
DataValueField="Name" AutoPostBack="True" >
</asp:DropDownList>
c# code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label0.Text = "Specialities";
Label1.Text = "Category";
Label2.Text = "Locations";
ddSpec.Items.Insert(0, new ListItem("Select a spec", "0"));
ddCategory.Items.Insert(0, new ListItem("Select a Category", "0"));
ddLocation.Items.Insert(0, new ListItem("<Select a Location>", "0"));
populattePage();
}
}
public void populattePage()
{
getlocation();
// getCategory()
}
public static void getlocation()
{
DataClasses_DataContext dc = new DataClasses_DataContext();
List<string> locations = (
from a
in dc.Locations
select a.Name).ToList();
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataValueField = "ID";
ddLocation.DataTextField = "Name";
ddLocation.SelectedIndex = 0;
ddLocation.DataBind();
}
I now have the Error """"DataBinding: 'System.String' does not contain a property with the name 'Name'.""" the code in the """page load""" class adds items to the drop downs however when i call the get locations class I get this error, Please help thanks in advance
There are two issues here. First - if you are going to use 2 properties of the Location object, you should use this object as a data source. No point to extract separate list of strings for this:
ddLocation.DataSource = dc.Locations.ToList();
This will resolve your exception. Also this line:
DropDownList ddLocation = new DropDownList();
should not be here, just remove it. You already have your drop down initialized.
Second issue - if you want some default item to appear in the list, you should insert it after the data binding:
populattePage();
ddLocation.Items.Insert(0, new ListItem("<Select a Location>", "0"));
ListItems have the properties "Text" and "Value". So when you create one, you can only use those properties for the drop down list text/value fields. You need to change
<asp:DropDownList Width="150px" ID="ddLocation" runat="server"
AppendDataBoundItems="True"
DataTextField="Text"
DataValueField="Value" AutoPostBack="True" >
</asp:DropDownList>
A simple way to get your location would be
List<ListItem> locations = (from a in dc.Locations
select new ListItem()
{
Text = a.Name,
Value = a.Name
}).ToList();
Then append that to your list.
So the problem is the data source you're binding to is primarily string. When you set the DataValueField and DataTextField properties, it calls the reflector and asks the object its being bound to, to give it the property. Since I'm assuming the a.Name in the query is a string, it would not have a "Name" or "Id" property. A simple solution to this would be to create an ID and Name property.
This might help illustrate what I'm trying to say. (also please camel-case your function names if you plan to do C# it helps us maintenance programmers :))
public static void GetLocation()
{
DataClasses_DataContext dc = new DataClasses_DataContext();
var locations = (
from a
in dc.Locations
select new { Name = a.Name, Id = a.Id }).ToList(); // this can be Id = a.Name or whatever too
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataValueField = "ID";
ddLocation.DataTextField = "Name";
ddLocation.SelectedIndex = 0;
ddLocation.DataBind();
}
Hope that helps!
Edit: I solved the problem by including an filterexpression on my gridview and a textbox for the search. That way I could pass the search query directly without doing all kinds of fancy stuff.
I have made a basic searchfunction. In that searchfunction, I have included a hyperlink to see more information:
<asp:HyperLink ID="lnkSelect" runat='server' NavigateUrl='<%# String.Format("~/CompanyActive.aspx?id={0}", Eval("CompanyID")) %>'>Select</asp:HyperLink>
It passes on the CompanyID to my mainpage (CompanyActive) where I have a gridview with paging.
However my problem is that it doesnt go to the specific page/place where the record is located. It just shows the first page.
I think I need to put some kind of code into my pageload event on CompanyActive, but I dont know which commands I should be using.
are you using a datatable to fill your gridview ?
if so and you know the ID is not going to change you could do the navigation on record ID
here is a link to a similar question on Stackoverflow
How to go to particular record in gridview
Hope this helps
Martyn
Example
You are using this as your link button
<asp:HyperLink ID="lnkSelect" runat='server' NavigateUrl='<%# String.Format("~/CompanyActive.aspx?id={0}", Eval("CompanyID")) %>'>Select</asp:HyperLink>
to use the code from the other article just modify the code like this
private void BindProductGrid()
{
product ID = Request.QueryString["id"]; // id is the name same as what you passed as a querystring
DataTable tblProducts = getAllProducts();
GridProducts.DataSource = tblProducts;
bool needsPaging = (tblProducts.Rows.Count / GridProducts.PageSize) > 1;
if (ProductID == -1)
{
this.GridProducts.PageIndex = 0;
this.GridProducts.SelectedIndex = -1;
}
else
{
int selectedIndex = tblProducts.AsEnumerable()
.Select((Row, Index) => new { Row, Index })
.Single(x => x.Row.Field<int>("ProductID") == ProductID).Index;
int pageIndexofSelectedRow = (int)(Math.Floor(1.0 * selectedIndex / GridProducts.PageSize));
GridProducts.PageIndex = pageIndexofSelectedRow;
GridProducts.SelectedIndex = (int)(GridProducts.PageIndex == pageIndexofSelectedRow ? selectedIndex % GridProducts.PageSize : -1);
}
GridProducts.DataBind();
}
That way the ID is the companies id that you passed from the other page
when i execute the code i get 4 checkboxs and i checked/selected all 4 checkbox and when i try to debug the code, it does count that i have 4 checkbox but all 4 checkbox is selected=false.
what i am missing in code?
<asp:checkboxlist id="chk" runat="server" ondatabinding="chk_DataBinding"
ondatabound="chk_DataBound">
</asp:checkboxlist>
List<String> roles = new List<string>();
for (int i = 0; i < chk.Items.Count; i++)
{
if (chk.Items[i].Selected)
{
roles.Add(chk.Items[i].Value);
}
}
Your logic is consistent with the basic CheckBoxList given on the ListControl.Items page, and from personal experience, checking the .Selected property of the ListItem should work fine.
Check to make sure you aren't re-populating the CheckBoxList before you hit the "if checked" logic - if I had to guess, I'd say there's a good chance you're losing the list on every postback. The simple solution is don't call your databinding logic if it's a postback.
public string[] CheckboxListSelections(System.Web.UI.WebControls.CheckBoxList list)
{
ArrayList values = new ArrayList();
for(int counter = 0; counter < list.Items.Count; counter++)
{
if(list.Items[counter].Selected)
{
values.Add(list.Items[counter].Value);
}
}
return (String[]) values.ToArray( typeof( string ) );
}