asp.net visibility of button depended on DataTable row value - asp.net

I would like to add button to ListView only for some of rows. I have something like "online chat" and I want to add delete option only for one user. It is complicated because I would like to have "delete" button only in rows which are these user's messages. Messages are saved in DataBase.
.aspx
<td><asp:Button ID="Button1" runat="server" Visible = <%# Eval("BUTTON") %>
.aspx.cs
DataColumn newColumn = new DataColumn("BUTTON", typeof(bool));
dataTable.Columns.Add(newColumn);
foreach (DataRow row in dataTable.Rows)
{
if (row["USER_NAME"].ToString() == "Franek")
row["BUTTON"] = true;
else
{
row["BUTTON"] = false;
}
}
sqlDataAdapter.Fill(dataTable);
MessagesView.DataSource = dataTable;
MessagesView.DataBind();
Communicat of error is (image)
Thank you and have a nice day

Try adding the column BUTTON after sqlDataAdapter.Fill(dataTable);.
sqlDataAdapter.Fill(dataTable); would fill the Data Table from Database and it may be resetting the values of "BUTTON" column.
sqlDataAdapter.Fill(dataTable);
DataColumn newColumn = new DataColumn("BUTTON", typeof(bool));
dataTable.Columns.Add(newColumn);
foreach (DataRow row in dataTable.Rows)
{
if (row["USER_NAME"].ToString() == "Franek")
row["BUTTON"] = true;
else
{
row["BUTTON"] = false;
}
}
MessagesView.DataSource = dataTable;
MessagesView.DataBind();

Related

Dynamically added controls remove when dropdown event fired in the datalist in user control

I am working on an ASP.NET VB.NET web form - a reservation web application, in which only one aspx page and rest are user-control page.
At run-time of aspx page, user controls load as per step and name define in db, like in below link.
ASP.NET Custom user control to add dynamically
In the first step, the first user-control is bind in page-init which is used to shows reservation availability detail in .NET datalist control like (see images).
All the details are bind to generate run-time control via data-list's item_databound event.
ImageOfRoom (asp.net Image Control) - on click popup will open with scroll functionality
Name (direct databound)
Amenities (icon(s)) - dynamically add from db.
No. of room as per room type (asp.net dropdown control) - dynamically add from db and on selected index changed, need another dropdown bind in same row and on change of adult dropdown price will vary.
Total price (direct databound)
Book now (button)
Now issue is whenever any event of datalist(click on romm-image or dropdown selected index changed) fired, the dynamic control remove like ammenities, dynamic dropdown of other row etc.
What I tried as :- ispostback, relevant event of page-life cycle, ajax-jquery, viewstate.
I checked this also, But no luck. :
Dynamically added controls in Asp.Net
I analyze that, the user-control is always rebound and then event fired, but no datalist rebind and thus no - databound event fire and finally dynamic control is removed. If you wish, I will share the code too (but its huge code).
So question is how to retain the dynamic controls and its value when dropdown selected index changed or image click event fired in datalist in usercontrol?
I am not used update-panel, does that work? If yes, then please give sample data.
Good to answer with sample data. Even please suggest that if possible via any other control like grid-view or else, then I ready to change it.
Updated
This is my code
Load User Control code
In aspx page, usercontrol define to load another user control as per current step. This “uc” user control tag in aspx page.
<div id="divPlaceholder" runat="server">
<uc:DynamicControlHost ID="ucDynamicControlHost" runat="server" />
</div>
In page_load as well as page_prerender( ispostback ) , the below code execute to load runtime user-control.
public Control SetUserControlPath(string path)
{
Control c = null;
if (this.dynamicAllContent.Controls.Count > 0)
{
//Check that the new control is not the same as the current control
if (!this.UserControlPath.Equals(path))
{
//Remove the old item because we can not simply replace them!
this.dynamicPHAllContent.Controls.Clear();
c = Page.LoadControl(path + ".ascx");
c.ID = path;
//Add New Item
this.dynamicAllContent.Controls.Add(c);
lock (_userControlLockObject)
{
//Store the new path
_strUserControl = path;
}
}
}
else
{
c = Page.LoadControl(path + ".ascx");
c.ID = path;
this.dynamicAllContent.Controls.Add(c);
_strUserControl = path;
}
return c;
}
Structure of datalist in usercontrol
<asp:UpdatePanel ID="EmployeesUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:DataList ID="dlLodgingAvailableDetails" ShowHeader="true" OnSelectedIndexChanged="dlLodgingAvailableDetails_SelectedIndexChanged" runat="server" CellPadding="2" CellSpacing="2" BorderWidth="1px" BorderColor="Black"
OnItemDataBound="dlLodgingAvailableDetails_ItemDataBound" BorderStyle="Solid" GridLines="Horizontal" HorizontalAlign="Justify">
<HeaderStyle CssClass="submit_butt"></HeaderStyle>
<HeaderTemplate>
Lodging Item Type Details
<asp:Button ID="btnBookRoom" runat="server" Text="Book Rooms" CssClass="submit_butt" OnClick="btnBookRoom_Click" />
</HeaderTemplate>
<ItemTemplate>
<table cellpadding="2" cellspacing="0" border="1" style="width: 100%";>
<tr>
<td style="width:170px">
<asp:ImageButton ID="imgLodging" OnClick="imgLodging_Click" commandargument='<%# Eval("ItemTypeId") %>'
runat="server" ImageUrl='<%# Eval("Photo") %>' Width="150px" Height="120px" />
</td>
<td style="width:180px">
<b>Name</b><br />
<span><%# Eval("ItemTypeName") %></span><br />
<b>Occupancy</b> <span><%# Eval("Occupancy") %></span>
<br />
<asp:panel ID="placeholderAmmenities" runat="server" Visible="True" ></asp:panel>
</td>
<td style="width:100px">
<b>Room</b><br />
<asp:hiddenfield runat="server" ID="hdnItemTypeId" Value='<%# Eval("LodgingItemTypeId") %>' />
<asp:DropDownList ID="ddlAvailable" runat="server"
AppendDataBoundItems="True" SelectedValue='<%# Bind("LodgingReservationsAvailable") %>' >
<asp:ListItem Value="0" Text="0"/>
<asp:ListItem Value="1" Text="1"/>
<asp:ListItem Value="2" Text="2"/>
</asp:DropDownList>
</td>
<td>
</td>
<td style="width:100px">
<div id="dvadult" runat="server"></div>
<asp:placeholder runat="server" ID="PlaceHolderAdult" ViewStateMode="Enabled" EnableTheming="False" Visible="True" ></asp:placeholder>
</td>
<td style="width:50px">
<asp:Label runat="server" ID="lblnumbernight" ></asp:Label>
</td>
<td style="width:50px">
<asp:placeholder ID="placeholderPrice" runat="server" Visible="True"></asp:placeholder>
</td>
<td style="width:50px">
<b>Total</b><br />
<asp:Label runat="server" ID="lblTotalAmount" ></asp:Label>
</td>
<td style="width:100px">
<asp:Button ID="btnBookRoom" runat="server" Text="Book Rooms" CssClass="submit_butt" />
</td>
</tr>
</table>
</ItemTemplate>
<SeparatorStyle BackColor="Lime" Font-Bold="False" Font-Italic="False" Font-Overline="False" Font-Strikeout="False" Font-Underline="False" HorizontalAlign="Center" />
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
Datalist item data bound event code (its inside image binding , price related field add and also creating the dynamic control as per the condition)
protected void dlLodgingAvailableDetails_ItemDataBound(object sender, DataListItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Image img = e.Item.FindControl("imgLodging") as Image;
if (img != null)
{
string bytesval = ((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[3].ToString();
if (string.IsNullOrWhiteSpace(bytesval)) return;
byte[] bytes = (byte[])((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[3];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
img.ImageUrl = "data:image/png;base64," + base64String;
}
DropDownList ddlList = e.Item.FindControl("ddlAvailable") as DropDownList;
Label lbldipositamount = e.Item.FindControl("lblTotalAmount") as Label;
Label lblnumbernight = e.Item.FindControl("lblnumbernight") as Label;
var PlaceHolderAmmenities = e.Item.FindControl("placeholderAmmenities") as Panel;
ddlList.Attributes.Add("onchange", " openLodgingNumber1(this,'" + ddlList.SelectedValue + "');");
int? LodgingItemTypeId = Convert.ToInt32(((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[1]);
DataSet ds = new DataSet();
ds = LodgingData.SelectLodgingItemTypeAmenityDateSet(LodgingItemTypeId);
DataTable dt = new DataTable();
if (ds != null)
{
dt = ds.Tables[0];
if (dt.Rows.Count > 0)
{
for (int j = 0; j < dt.Rows.Count; j++)
{
Image image = new Image();
image.ID = "imgAmmenities" + j + DateTime.Now.ToString();
string bytesval = dt.Rows[j]["AmenityIcon"].ToString(); //((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[4].ToStrin();
//if (string.IsNullOrWhiteSpace(bytesval)) return;
if (bytesval != string.Empty)
{
byte[] bytes = (byte[])dt.Rows[j]["AmenityIcon"];
string base64String = Convert.ToBase64String(bytes, 0, bytes.Length);
image.ImageUrl = "data:image/png;base64," + base64String;
image.Height = 20;
image.Width = 20;
image.EnableViewState = true;
PlaceHolderAmmenities.Controls.Add(image);
PlaceHolderAmmenities.Controls.Add(new LiteralControl(" "));
}
}
}
}
decimal PriceTotal = 0;
var PlaceHolderPrice = e.Item.FindControl("placeholderPrice") as PlaceHolder;
DataSet dsprice = new DataSet();
dsprice = LodgingData.SelectLodgingItemTypePrice(LodgingItemTypeId);
if (dsprice != null)
{
DataTable dtprice = new DataTable();
dtprice = dsprice.Tables[0];
if (dtprice.Rows.Count > 0)
{
DateTime fromdate = Convert.ToDateTime(txtFromDate.Text);
DateTime todate = Convert.ToDateTime(txtToDate.Text);
double daterange = ((todate - fromdate).TotalDays + 1);
lblnumbernight.Text = daterange.ToString();
//for (DateTime date = fromdate; date >= todate; date.AddDays(1))
for (int d = 0; d < Convert.ToInt32(daterange); d++ )
{
DateTime date = fromdate.AddDays(d);
//DataView dv = new DataView(dtprice);
DataTable dtprice1 = new DataTable();
DataRow[] rows = dtprice.Select("#" + date + "# >= PriceStartDate AND" + "#" + date + "# <= PriceEndDate");
if (rows.Length > 0)
{
dtprice1 = rows.CopyToDataTable();
}
if (dtprice1.Rows.Count > 0)
{
for (int j = 0; j < dtprice1.Rows.Count; j++)
{
Label lbl = new Label();
string dayofweek = dtprice1.Rows[j]["DayOfWeekId"].ToString();
if (dayofweek.Trim() == eDayOfWeek.All.ToString().Trim())
{
lbl.ID = "lbl" + j;
lbl.Text = dtprice1.Rows[j]["Price"].ToString();
PriceTotal += Convert.ToDecimal(dtprice1.Rows[j]["Price"]);
PlaceHolderPrice.Controls.Add(lbl);
PlaceHolderPrice.Controls.Add(new LiteralControl("<br />"));
}
else if (Convert.ToInt32(dayofweek) == Convert.ToInt32(date.DayOfWeek + 1))
{
lbl.ID = "lbl" + j;
lbl.Text = dtprice1.Rows[j]["Price"].ToString();
PriceTotal += Convert.ToDecimal(dtprice1.Rows[j]["Price"]);
PlaceHolderPrice.Controls.Add(lbl);
PlaceHolderPrice.Controls.Add(new LiteralControl("<br />"));
}
}
}
else
{
DataView dv1 = new DataView(dtprice);
dv1.RowFilter = "PriceStartDate IS NULL OR PriceEndDate IS NULL";
//dv1.RowFilter = "PriceStartDate == null and PriceEndDate == null";
DataTable dtprice2 = new DataTable();
dtprice2 = dv1.ToTable();
for (int j = 0; j < dtprice2.Rows.Count; j++)
{
Label lbl = new Label();
string dayofweek = dtprice2.Rows[j]["DayOfWeekId"].ToString();
if (dayofweek.Trim() == eDayOfWeek.All.ToString().Trim())
{
lbl.ID = "lbl" + j;
lbl.Text = dtprice2.Rows[j]["Price"].ToString();
PriceTotal += Convert.ToDecimal(dtprice2.Rows[j]["Price"]);
PlaceHolderPrice.Controls.Add(lbl);
PlaceHolderPrice.Controls.Add(new LiteralControl("<br />"));
}
else if (Convert.ToInt32(dayofweek) == Convert.ToInt32(date.DayOfWeek + 1))
{
lbl.ID = "lbl" + j;
lbl.Text = dtprice2.Rows[j]["Price"].ToString();
PriceTotal += Convert.ToDecimal(dtprice2.Rows[j]["Price"]);
PlaceHolderPrice.Controls.Add(lbl);
PlaceHolderPrice.Controls.Add(new LiteralControl("<br />"));
}
}
}
}
}
}
lbldipositamount.Text = PriceTotal.ToString();
// var amount = ((System.Data.DataRowView)(e.Item.DataItem)).Row.ItemArray[3];
int selectedvalue = Convert.ToInt32(ddlList.SelectedItem.Text);
if (selectedvalue != 0)
{
double totalamount = selectedvalue * Convert.ToDouble(PriceTotal);
lbldipositamount.Text = totalamount.ToString();
}
}
}
catch (Exception)
{
throw;
}
}
On dynamically genereted dropdown selection event fired
In above even add this dropdown dynamically, now when this control's event is called , further dynamic control is adding as per the condition.
Issue is this event remove the dynamic other control as well even for other row of the previous selection is hidden or lost , so we retain the dynamic control in any post back and event fire.
protected void ddlAvailable_SelectedIndexChanged(object sender, EventArgs e)
{
// if (UserControlTextBoxChanged != null) dlLodgingAvailableDetails_ItemDataBound(sender, e);
//dlLodgingAvailableDetails.ItemDataBound += new DataListItemEventHandler(dlLodgingAvailableDetails_ItemDataBound);
double amount = 0;
var ddlList = (DropDownList)sender;
var row = (DataListItem)ddlList.NamingContainer;
//get the Id of the row
DataSet ds = new DataSet();
int? Id = Convert.ToInt32(((HiddenField)row.FindControl("hdnItemTypeId")).Value);
double? tamount = Convert.ToDouble(((Label)row.FindControl("lblTotalAmount")).Text);
int? groupid = Convert.ToInt32(ddlLodgingGroup.SelectedValue);
int selectedvalue = Convert.ToInt32(ddlList.SelectedItem.Text);
DateTime? startdate = Convert.ToDateTime(txtFromDate.Text);
DateTime? enddate = Convert.ToDateTime(txtToDate.Text);
ds = LodgingData.SelectLodgingItemTypeDataSet(startdate, enddate, groupid);
DataTable dt = new DataTable();
DataView dv = new DataView();
if (ds != null)
{
dt = ds.Tables[0];
dv = dt.DefaultView;
dv.RowFilter = "LodgingItemTypeId=" + Id;
}
dt = dv.ToTable();
if (dt.Rows.Count > 0)
{
if (tamount != null)
{
amount = Convert.ToDouble(tamount);
}
}
//amount = Convert.ToDouble(((Label)row.FindControl("lblTotalAmount")).Text);
var PlaceHolder1 = ((PlaceHolder)row.FindControl("PlaceHolderAdult"));
double totalamount = 0;
if (selectedvalue != 0)
{
totalamount = selectedvalue * Convert.ToDouble(amount);
((Label)row.FindControl("lblTotalAmount")).Text = totalamount.ToString();
Label lblAdult = new Label();
lblAdult.ID = "lblAdult";
lblAdult.Text = "Adult";
lblAdult.Font.Bold = true;
PlaceHolder1.Controls.Add(lblAdult);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
else
{
totalamount = amount;
}
for (int j = 0; j < selectedvalue; j++)
{
DropDownList ComboBox = new DropDownList();
ComboBox.ID = "ComboBox" + j;
ComboBox.AutoPostBack = false;
ComboBox.Attributes.Add("runat", "server");
ComboBox.Items.Add(new ListItem("0", "0"));
ComboBox.Items.Add(new ListItem("1", "1"));
ComboBox.Items.Add(new ListItem("2", "2"));
ComboBox.SelectedIndexChanged += new EventHandler(Dynamic_Method);
PlaceHolder1.Controls.Add(ComboBox);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
}
}
I'm not sure how much this will solve for you, but here is an example of preserving a row of data in a gridview with a templatefield containing a dynamically generated dropdownlist
I broke the process into 2 parts
1) Save data currently in Gridview to a session variable
2) Recreate, source, and bind controls
Here's saving the values in the gridview. I use a recursive find control formula I found on this site (but don't remember from where) because my controls are generated and placed inside the gridview row without unique names. For ex. the tbxA that exists in row 1 is different than the tbxA in row 2. This may not apply to you - the key is to find all controls you want to save the values of.
Private Sub SaveValues()
Dim savedTable As New DataTable
savedTable.Columns.Add(New DataColumn("A"))
For i = 0 To GridView1.Rows.Count - 1
Dim existing(0) As Object
existing(0) = TryCast(FindControlRecursive(GridView1.Rows(i), "ddlA"), DropDownList).SelectedValue
savedTable.Rows.Add(existing)
Next
Session("GhostTable") = savedTable
End Sub
Then in Page_Load under(when it IS a postback) set the gridview datasource to the session variable, and databind it. This will trigger the following code for every row:
Keep in mind I also have the datasource of the dropdown list stored in a session variable on page load. This allows the datasource and databind to occur for the dropdown every time it is generated.
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
'Handles databinding of each gridview1 row ddl to gridview templatefield
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ddlA As New DropDownList()
ddlA.DataSource = Session("lengthList")
ddlA.DataBind()
ddlA.ID = "ddlA"
ddlA.SelectedValue = TryCast(e.Row.DataItem, DataRowView).Row.Item("A").ToString()
e.Row.Cells(1).Controls.Add(ddlA)
End if
End Sub
The ddlA.SelectedValue = TryCast(e.Row.DataItem, DataRowView).Row.Item("A").ToString() is what preserves the data after any postback. It determines which row is being bound, and then repopulates the control with whatever it previously was.
Hope this helps!
To make sure that the gridview is populated every time, call SaveValues in your event handlers.
Protected Sub ddlEmpNumber_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlEmpNumber.SelectedIndexChanged
'Do whatever on selected index change, then the following:
Call SaveValues()
GridView1.DataSource = Session("GhostTable")
GridView1.DataBind()
End Sub
Do it all in the page_init
You're wiring up the eventhandler in the ASP part like this:
<asp:DataList ID ... OnSelectedIndexChanged="dlLodgingAvailableDetails_SelectedIndexChanged" ...
and then in code of the handler attempting to re-wire the other ones:
ComboBox.SelectedIndexChanged += new EventHandler(Dynamic_Method);
Any time you do dynamic stuff on a webforms page, all setup including event handler wireup must be in the page_init. When events run, re-wiring won't work. For what you're doing (asp: ... and during a method call), it's ending up in the wrong part of the lifecycle and the right things aren't there to either add the javascript to call doPostback, or if that runs the __eventargs, etc. have data for controls that aren't built yet (event postbacks are checked for AFTER page init so you have to create the controls before that check) and therefore get ignored.
Note - probably you know this but you have to give controls unique IDs, generally can by done if you have a numeric primary key by just appending to the datarows. (might have to do this manually to child controls in user control, have had to do this with usercontrols in page_init, hopefully you won't)
I work on a big app that dynamically builds every screen in webforms (from a UI generator) in the page-init. All work is done in events, they work like a charm! Page_load is basically empty. Get to know the asp page lifecycle - it's a booger but easier than rewriting your app in HotTowel (although think about that the next app ;-)
Pretty good diagram: http://blogs.msdn.com/b/aspnetue/archive/2010/01/14/asp-net-page-life-cycle-diagram.aspx
Good luck!
I have done every thing as above suggested and other google search site too. But it refresh the data and every time it rebind all dynamic object in the grid.
Finally I have done every thing based on javascript and jquery, without that dynamic control always rebind which I don't want. So any body who are stuck in this situation forgot to r and d and work with javascript/ webmethod with dynamic controls.
Thank all who given an answer

GridView - Removing Edit and Delete columns while exporting to Excel

Thank you for viewing my question and helping. I have a asp.net application built in C#. The application has a simple gridview. I have a button to export the gridview into excel, which works as well. However, my gridview has a edit link in column 1 and a delete button in column 2. Both if these columns export to excel as well. How do I stop these two columns from exporting? I have tried a few things:
GridView1.Columns.RemoveAt(0);
GridView1.Columns.RemoveAt(1);
and...
GridView1.Column(0).visible = false;
I did a data bind after each of these while trying, but it simply does not work. I'll post my code below, and maybe someone can help me out! Thanks!
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition",
string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grdGridView.RenderControl(htmlWrite);
GridView1.Columns.RemoveAt(0);
Response.Write(stringWrite.ToString());
Response.End();
GridView1.AllowPaging = false;
}
The girdview has the edit feature set to true, and the delete button is a template field as below:
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" CommandName="Delete" runat="server" Text="Delete" CssClass="okbutton" OnClientClick="return confirm('Are you sure you want to delete this entry?');" />
</ItemTemplate>
</asp:TemplateField>
You need to hide the individual cells in the header and data rows, like this:
// Hides the first column in the grid (zero-based index)
GridView1.HeaderRow.Cells[0].Visible = false;
// Loop through the rows and hide the cell in the first column
for (int i = 0; i < GridView1.Rows.Count;i++ )
{
GridViewRow row = GridView1.Rows[i];
row.Cells[0].Visible = false;
}
GridView1.Columns[6].Visible = false;
For Columns:
GridName.Columns[index].Visible = false;
For rows:
Gridname.Rows[index].Visible = false;

Binding multiple Dropdowns and textfields

In my project I have 2 dropdowns 1 listbox and 1 textbox. I Have already bound the 2 dropdowns together "PostalDropDown" and "CityDropDown" from the database and it works fine, Then i bind the listbox also to the previous dropdowns and it works fine also!
My question here i still have the last Textbox which i want it to display the name which is also bound to the results of dropdowns.
I cannot figur it out because the textbox does not have the SelectValue property, so I cannot assign it like i did with my dropdowns or listbox like i did:
if (!IsPostBack)
{
IEnumerable<Tuple<string, string, string, string>> data = GetData();
DropDownListPostal.DataSource = data.Select(tuple => tuple.Item1).Distinct().ToList();
DropDownListPostal.DataBind();
DropDownListCity.DataValueField = "Item1";
DropDownListCity.DataTextField = "Item2";
DropDownListCity.DataSource = data;
DropDownListCity.DataBind();
ListBox1.DataValueField = "item1";
ListBox1.DataTextField = "Item4";
ListBox1.DataSource = data;
ListBox1.DataBind();
}
}
and then i view the result on this on the selectedindexchanged on first dropdown:
protected void DropDownListPostal_SelectedIndexChanged1(object sender, EventArgs e)
{
//DropDownListPostal.ClearSelection();
ListBox1.ClearSelection();
DropDownListCity.ClearSelection();
var postal = DropDownListPostal.SelectedValue;
var listItem = DropDownListCity.Items.FindByValue(postal);
var street = ListBox1.Items.FindByValue(postal);
listItem.Selected = true;
street.Selected = true;
Can anyone show me how to add the rest of the database results on a textbox?
I can put the whole code for the page if you all want.
Cheers
If you really want to show all of the items in a Textbox which is quite strange you can display them comma seperated like this
TextBoxId.Text = String.Join(",", data.Select(op => op.Name));
Where Name is the property that contains the property you want to display in textbox
Edit
If you want to display the selected items of Listbox then loop on its item and check if the item is selected then display it in your textbox.
foreach (ListItem item in ListBox1.Items)
{
if (item.Selected)
{
txtval.Text += " " + item.Text +"/"+ dropdowncity.SelectedItem.Text +"/"+ dropdownpostal.SelectedItem.Text;
}
}

Bind RadcomboBox with multiple columns from Datatable

I would like to bind 'Id', 'Name' and 'Email' from DataTable to RadComboBox. It's possible with ItemTemplate. But I don't want to display 'Email' column in the RadComboBox. I want display 'Email' in the label when the selectedIndexChanged. Is this possible?
Thank you..
Yes, you can bind these three items within the RadComboBox by using the template. Check out this demo: http://demos.telerik.com/aspnet-ajax/combobox/examples/functionality/templates/defaultcs.aspx
Also, to display email when an item is selected, set the DataTextField="Email", which is the value that should appear when the selection is made.
HTH.
adding custom attributes to the RadComboBox is also a good option.
protected void RadComboBox_ItemsRequested(object sender, Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs e)
{
try
{
RadComboBox myRadComboBox = (RadComboBox)sender;
_rowsOfData = Db.getPeopleOfInterest();
foreach (row _row in _rowsOfData)
{
RadComboBoxItem item = new RadComboBoxItem
{
Text = _row.Name,
Value = _row.Id.ToString()
};
string eMail = _row.Email;
item.Attributes.Add("Email", Email);
item.DataBind();
}
}
catch (Exception ex)
{
HandleException(ex, true);
}
}
Then to display that on the GUI just use something like :
<td>
<%# DataBinder.Eval(Container, "Attributes['Name']")%>
</td>

Add "Select" item in DropDown

I am using ASP.NET dynamic data. In Insert.aspx page, I have a couple of dropdowns to be selected. The fields represented by Dropdown are Required fields in database. So dropdown does not show 'Select' as default option in dropdown. I want to add 'Select' option at top of other records from database shown in dropdown. Note that field is not Required field, hence 'Select' option is not being show over there by dynamic data by default. How can I accomplish this?
Add your "select" item after binding your dropdownlists by using Insert method :
myDropDownList.DataBind();
// To make it the first element at the list, use 0 index :
myDropDownList.Items.Insert(0, new ListItem("Select", string.Empty));
I would create a custom FieldTemplate for Required DropDown fields. Insert the "Select" item during the OnDataBinding event of the control. I would also have a client side RequiredFieldValidator to make sure something other than "Select" is chosen before it can post back.
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ForeignKeyRequired_Edit.ascx.cs"
Inherits="DDWANorthwind.DynamicData.FieldTemplates.ForeignKeyRequired_Edit" %>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="droplist">
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="DropDownList1" ErrorMessage="Selection Required"></asp:RequiredFieldValidator>
-
protected override void OnDataBinding(EventArgs e)
{
base.OnDataBinding(e);
if (Mode == DataBoundControlMode.Edit)
{
string foreignkey = ForeignKeyColumn.GetForeignKeyString(Row);
ListItem item = DropDownList1.Items.FindByValue(foreignkey);
if (item != null)
{
DropDownList1.SelectedValue = foreignkey;
}
}
else if (Mode == DataBoundControlMode.Insert &&
Column.IsRequired)
{
DropDownList1.Items.Insert(0, new ListItem("Select", ""));
}
}
-
you would have to use the UIHint attribute so that this FieldTemplate would be used over the default.
Adding a top element at index 0 works just fine, but LINQ offers another possibility, to return the "select" or "pick something" or "all" as part of the data. A drop-down list was databound to this function:
public static List<string> GetRegions()
{
using (NorthwindDataContext nw = new NorthwindDataContext())
{
IQueryable<string> regionQuery = nw.Customers
.Where(c => c.Region != null)
.OrderBy(c => c.Region)
.Select(c => c.Region)
.Distinct();
return (new List<string>() { "All" }).Concat(regionQuery).ToList();
}
}
//---Populate Category DropDownList
private void getData()
{
var category = (from c in CoffeeContext.tblProductTypes
select new { c.ProductType, c.Description }).ToList();
cbxCategory.DataTextField = "Description";
cbxCategory.DataValueField = "ProductType";
cbxCategory.DataSource = category;
cbxCategory.DataBind();
cbxCategory.Items.Insert(0, "--Select Type--");
cbxCategory.SelectedIndex = 0;
}
Select Top 1 '0' as valueField, '--Select--' as textField from dummtable
UNION
select ID,text from yourTable
Control from backend gives much more flexibility

Resources