how get value of aspxcombobox in code behind - asp.net

I have aspxcombobox(Devexpress)
asp.net :
<dx:ASPxComboBox ID="ASPxComboBox1" runat="server" DataSourceID="SqlDataSource1">
<Columns>
<dx:ListBoxColumn FieldName="cg_id" />
<dx:ListBoxColumn FieldName="cg_name" />
</Columns>
</dx:ASPxComboBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:TravelConnectionString %>" SelectCommand="SELECT * FROM [Categorys_Group]"></asp:SqlDataSource>
Code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("Accounting/Check.aspx?id=" + ASPxComboBox1.SelectedItem.GetValue("cg_name"));
}
When click button. i want to get value index selected of aspxcombobox.
I try get value of combobox, but it only return value first ( = 0 ).
WHo can help me? get value of aspxcombobox.

This problem may be caused by wrong selectedItem or selectedIndex property or when aspxcombobox is empty etc.
MessageBox.show(ASPxComboBox1.Value != null? ASPxComboBox1.Value.ToString():string.Empty);
To skip from this error you should know ValueType property properly.
And also see it..
ASPxClientComboBox_GetSelectedItem

You have 2 choices:
on the code behind, create a switch case on the index selected, and bindes the data to comboBox accordingly.
on the data level: in your data base access layer, using your Data Provider class that fetches data from your database, you have to create a GET method that takes the SELECTED INDEX as a parameter, pass that SELECTED INDEX to a pre-defined STORED PROCEDURE and do a SELECT according to the choosen index.
I would suggest using the second solution for the following reasons:
no changes made on the code behind side.
fetch is done on the database level according to the selected index, which assures the correct data imported. --> Your Data Source is Bound earlier in the process.
small changes are made on the STORED PROCEDURE :)
Best Regards,
ANDOURA

Related

How to populate a dropdown list in asp.net from a DB table?

I want to populate a dropdown list with values from a table I created. I only want to populate the list with one of the fields- the languages in my table. I think I have connected to the data source correctly, but I don't know what I have to do to get the values into the list. I can enter my own values but I'd rather have this automated.
This is what I have so far, but I'm guessing there's more to it than just linking the list to the data source.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HBshareIndexConnectionString %>"
SelectCommand="SELECT * FROM [Web_Metrics] WHERE ([LCID] = #LCID)">
<SelectParameters>
<asp:QueryStringParameter Name="LCID" QueryStringField="LCID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Label ID="Label1" runat="server" Text="Select LCID: " ></asp:Label>
<asp:DropDownList ID="DropDownList1" Width="150px" runat="server" DataSourceID="SqlDataSource1" DataTextField="LCID" DataValueField="LCID">
<asp:ListItem>Select LCID...</asp:ListItem>
</asp:DropDownList>
Thanks for the help. I got the dropdown list populated now, but I was wondering how do I actually get the repeater I'm using to display the details of the LCID the person selects? I've seen people talking about page.isPostback but I don't know what that is or if it works with my current setup. I need to somehow get the LCID they selected and then refresh the page to show the details of that LCID. Does anyone have any ideas?
Your problem is that you're trying to define list items and a data source.
If you want to insert a "Select an item.." option, I would suggest prepending it to your resultset (getting it to always be first with a UNION and ORDER BY could be difficult depending on your fields) or inserting it after databinding in your code behind:
Modification to DropDownList1s attributes:
<asp:DropDownList ID="DropDownList1" Width="150px" runat="server" DataSourceID="SqlDataSource1" DataTextField="CountryName" DataValueField="LCID" OnDataBound="InsertChooseItem" />
C#:
protected void InsertChooseItem(object sender, EventArgs e)
{
ListItem selectOnePlease = new ListItem("Select LCID..", 0);
DropDownList1.Items.Insert(0, selectOnePlease);
}
VB:
Protected Sub InsertChooseItem(sender As Object, e As EventArgs)
Dim selectOnePlease As New ListItem("Select LCID..", 0)
DropDownList1.Items.Insert(0, selectOnePlease)
End Sub
You've specified the select parameter to be a query string, so the data in your DropDownList will only be populated when the URL resembles something like:
http://{Your server name}/Default.aspx?LCID=1
That doesn't make any sense though because the LCID column in your table should be unique, so although this will work there will only be one value in the drop down list.
I think what you want is to display all the languages from the database in the drop down, here's an example:
<asp:SqlDataSource ID="sqlDS" runat="server"
ConnectionString="<%$ ConnectionStrings:HBshareIndexConnectionString %>"
SelectCommand="SELECT LCID,Language FROM [Web_Metrics]">
</asp:SqlDataSource>
<asp:DropDownList ID="ddlLanguages" AppendDataBoundItems="true" Width="150px" runat="server" DataSourceID="sqlDS" DataTextField="Language" DataValueField="LCID">
<asp:ListItem>Select Language</asp:ListItem>
</asp:DropDownList>
Just a note, you should never display the ID to the client, it's totally meaningless to them, the ids are mostly used by developers in the background that's why in the drop down I set the:
DataTextField="Language" (This is the language name visible to the user)
DataValueField="LCID" (Not visible to the user, but useful for any additional processing in code behind)
AppendDataBoundItems="true" - this line of code will keep all the items you've manually added to the drop down, e.g "Select Language" and will append any data bound items e.g from a SQL table

Sending parameter to code behind from stored procedure

I'm using a FormView and binding it to a SqlDataSource using a stored procedure to edit a record. The thing is that after updating the record I need to call another function, which I'm doing using the onClick attribute of the button.
This function has to insert a few records into another table, using the ID of the record edited in the FormView. I know how to use SCOPE_IDENTITY when in the same stored procedure, but this time I need some logic that is easier to accomplish in the code-behind, but I don't know how to obtain the ID, so any leads would be great.
Here is the button:
<asp:Button ID="EditButton" runat="server" CausesValidation="True" CommandName="Update"
Text="Edit" OnClick="setProcessProgress" />
And here is a stripped down version of the code behind:
protected void setProcessProgress(object sender, EventArgs e)
{
int ID_p;
ID_p = ; //TODO: Here I need to obtain the ID of the last edited record from the EditButton
setProgress(ID_p);
}
The stored procedure is a simple UPDATE statement.
I'm thinking of passing a parameter to the code behind, but not sure how to, perhaps something like this OnClick="setProcessProgress(#id)"
try like this, and you need to attach OnCommand="CommandEventHandler" event handler to your button . check for More Info Button.Command
<asp:Button ID="EditButton" runat="server" CausesValidation="True" CommandName="Update"
Text="Edit"
CommandArgument="1"
OnCommand="CommandBtn_Click" />
and the code for to get the ID
protected void CommandBtn_Click(Object sender, CommandEventArgs e)
{ if (e.CommandName == "Update")
{
yourID =Convert.ToInt32(e.CommandArgument);
}
}
You can use out parameter for update store procedure. This will give you the ID after
update.
Then you can use the ID for your insert.
http://blogs.msdn.com/b/spike/archive/2009/05/07/a-simple-example-on-how-to-get-return-and-out-parameter-values-using-ado-net.aspx

ASP.NET Gridview Templatefield with multiple items

I am creating a web application in ASP.net/VB.NET and I have an issue with the GridView control.
Currently, I have the GridView populated with data from the DB and I've also coded the update button to allow the user to edit any necessary information through a form that pops up.
What I'd like to do, if possible, is add a button to the two right columns(I already put one in the Dock Out Time column) which will be invisible if the column is set or will set the current time to the column. Setting the time for those two columns is already handled through the update form, but my supervisor asked me to try and see if this was possible.
Those two Time columns are TemplateFields(since I format the display time from what is actually in the DB) and I added an asp button in the ItemTemplate for that Set Button in the picture.
Is this even possible to do and if so, how would I access this button in the code behind so I can add functionality(setting the time and hiding it if the column is not null)If it's not really possible to have two items like this in a TemplateField I can just make 2 extra columns for these buttons but I think this would look much cleaner.
Any input would be greatly appreciated. thank you for your time.
Yes this is possible, check this answer:
https://stackoverflow.com/a/11077709/1268570
Basically you need to handle the RowCommand event from the grid and identify each button with a command, optionally you can add arguments to each button when you bind, for example:
<asp:GridView runat="server" OnRowCommand="grdProducts_RowCommand"
ID="grdProducts">
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false"
CommandName="myLink" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' Text="Button"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
In code behind:
protected void grdProducts_RowCommand(object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "myLink":
this.lblMessage.Text = e.CommandName + " " + e.CommandArgument + " " + DateTime.Now.ToString();
// referenece to the current row
var row = this.grdProducts.Rows[int.Parse(e.CommandArgument.ToString())];
break;
default:
break;
}
}
After you update your grid in the RowCommand event, you should repopulate the grid data to render the changes

Dynamic Data - Selecting a table from a DropDownList to scaffold in a GridView

I have been struggling with this ASP.NET Dynamic Data problem for days now... I have a DropDownList containing the table names of all the tables in my data context (.dbml) file. When I select the DropDownList, it needs to scaffold the selected table in a GridView. My code works 100% in scaffolding the MetaTable in the GridView (it implements all the rules that I applied in my Meta Classes).
However, filtering only seems to work if I explicitly add the DynamicExpression in the declaration of the QueryExtender:
<asp:QueryExtender ID="GridQueryExtender" TargetControlID="GridDataSource" runat="server">
<asp:DynamicFilterExpression ControlID="FilterRepeater" />
</asp:QueryExtender>
This in turn requires me to specify the MetaTable explicitly in the LinqDataSource (linqdsData), either programmatically in the Page_Load or in the ASP.NET syntax.
Since the GridView gets scaffolded in the Page_Load part of the life-cycle, the above approach does not work for me, since it takes place in the Page_Init part of the life-cycle.
So my requirement is that as soon as I select another table to populate the GridView with from the DropDownList, the FilterRepeater needs to reflect the filters of the newly selected MetaTable.
Is there any way for me to programmatically update the FilterRepeater in the Page_Load so that it will contain the filters of the MetaTable that I selected in the DropDownList.
The following is some of my code:
ASP.NET Page Code-Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (ddlTable.SelectedIndex > 0)
{
string tableName = ddlDataType.SelectedValue;
linqdsData.TableName = tableName;
MetaTable mt = ASP.global_asax.DefaultModel.GetTable(tableName);
GridViewData.SetMetaTable(mt, mt.GetColumnValuesFromRoute(Context));
GridViewData.EnableDynamicData(mt.EntityType);
GridViewData.DataSourceID = linqdsData.ID;
}
}
ASP.NET Page:
<asp:Panel runat="server" ID="pnlFilters" CssClass="gridFilterCon" EnableTheming="True">
<div class="filterGridHeading">
Filter the grid by:</div>
<asp:QueryableFilterRepeater runat="server" ID="FilterRepeater">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("DisplayName") %>' OnPreRender="Label_PreRender"
CssClass="gridFilterLbl" />
<asp:DynamicFilter runat="server" ID="DynamicFilter" />
<br />
</ItemTemplate>
</asp:QueryableFilterRepeater>
<asp:Button ID="btnFilter" runat="server" Text="OK"
EnableTheming="False" UseSubmitBehavior="False" OnClick="btnFilter_Click" />
</asp:Panel>
<asp:GridView ID="GridViewData" runat="server" OnSelectedIndexChanged="GridViewData_SelectedIndexChanged"
OnPreRender="GridViewData_PreRender" OnRowDataBound="GridViewData_RowDataBound"
OnPageIndexChanged="GridViewData_PageIndexChanged" AllowPaging="True" PageSize="50" OnInit="GridViewData_Init">
<Columns>
...
</Columns>
<PagerTemplate>
<asp:GridViewPager ID="GridViewPager1" runat="server" />
</PagerTemplate>
<PagerSettings Mode="NumericFirstLast" NextPageText="Next" />
</asp:GridView>
<asp:LinqDataSource ID="linqdsData" runat="server" ContextTypeName="pdcDataContext"
OnSelected="linqdsData_Selected" OnSelecting="linqdsData_Selecting" EnableUpdate="True">
</asp:LinqDataSource>
<asp:QueryExtender ID="GridQueryExtender" TargetControlID="linqdsData" runat="server">
</asp:QueryExtender>
Your help will be greatly appreciated.
It sounds like you are trying to do a lot on one web page. This creates complications of the type you are experiencing: each table requires distinct filters and MetaTables. Trying to keep each item straight requires a bunch of switch and/or if...then statements. I recommend an alternate approach. Instead of doing all of this on one page:
Create a web page for each table
Setup the appropriate filters and MetaTables
Copy the DropDownList containing the table names of all the tables to each web page, and use it to redirect to the appropriate web page.
ASP.net Dynamic Data makes it easy to create web pages for each table. That is what scaffolding is all about. With the approach above, each web page will handle its own set of concerns that are focused on the particular table.
Hope this helps.

How to modify Bind("MyValue") in asp.net

I'm having headache with Time values and multiple time zones.
I'm storing new DateTime values in UTC time, but I face problem when I try to modify them using LinqDataSource and GridView.
I can easily show correct time in
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# TimeManager.ToLocalTime((DateTime)Eval("OrderDate")) %>' />
</ItemTemplate>
Currently this will add 1 hour to UTC time stored in DB.
However, binding back to source is not easy. Bind("OrderDate") cannot be modified like TimeManager.ToGlobalTime((DateTime)Bind("OrderDate")).
I was thinking of using OnUpdating event of LinqDataSource to update value to global time, but what if user modified other fields and not date field? Every time he updates record time value would be smaller for one hour.
Comparing old and new values also is not great because user can modify date portion of datetime and not time, which is influenced by time zones?
If I had way to show local time in gridview's all states then I could easily use OnUpdating of LinqDataSource.
Please share your thoughts...
Have you considered making the change to your model? Let's assume that the name of the object you are binding to is CustomerOrder. You could add the following class to your project (in the same namespace as your Linq objects):
public partial class CustomerOrder
{
public DateTime LocalOrderDate
{
get { return TimeManager.ToLocalTime(OrderDate); }
set { OrderDate = TimeManager.ToUTCTime(value); }
}
}
Now instead of binding to OrderDate, bind to LocalOrderDate. This will automatically make the UTC / Local Time conversion to the OrderDate.
(Note: I'm assuming you have TimeManager.ToLocalTime() and TimeManager. ToUTCTime() properly defined)
The way I've handled this sort of thing in the past is to use Eval in the EditItemTemplate as well. Let the user edit the item in local time. Then add OnItemUpdating handler for the gridview and add extract the value of the associated text box, convert it to global time, and add that to the new values dictionary. Bind the original value in (in global time) to a hidden field in the same template, which will populate the old values dictionary with the correct old time. You'll want to do the same thing on insertion in OnItemInserting although you obviously don't need the old value (since there isn't one).
EDIT: Usually I do my updates on a DetailsView not a GridView, thus the ItemUpdating/Inserting instead of RowUpdating/Inserting. Sample code below -- this example uses a pair of dropdown lists that allows the user to specific a location (choose a building and a location in the building, but it actually only maps the location in the database). On the back end it assigns initial values to the dropdowns in OnPreRender (not shown) and extracts the LocationID database field value from the location dropdown on ItemUpdating/Inserting (updating shown). The DetailsView is wrapped in an UpdatePanel and the population of the Location dropdown is done when the building dropdown selection changes. Note that since I'm updating the item (causing an update statement anyway) I don't care if the LocationID field gets overwritten on the update with the same value so I don't bother to keep the old value on the page.
<asp:TemplateField HeaderText="Location:" SortExpression="LocationId">
<EditItemTemplate>
<asp:DropDownList runat="server" ID="buildingDropDownList"
DataSourceID="buildingDataSource"
DataTextField="name"
DataValueField="abbreviation"
OnSelectedIndexChanged=
"buildingDropDownList_SelectedIndexChanged"
AutoPostBack="true" />
<asp:DropDownList runat="server" ID="locationDropDownList"
DataSourceID="locationsDataSource"
DataTextField="Name"
DataValueField="ID">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:DropDownList runat="server" ID="buildingDropDownList"
DataSourceID="buildingDataSource"
DataTextField="name"
DataValueField="abbreviation"
OnSelectedIndexChanged=
"buildingDropDownList_SelectedIndexChanged"
AutoPostBack="true"
AppendDataBoundItems="true">
<asp:ListItem Text="Select Building" Value="" />
</asp:DropDownList>
<asp:DropDownList runat="server" ID="locationDropDownList"
DataSourceID="locationsDataSource"
DataTextField="Name"
DataValueField="ID"
AppendDataBoundItems="true">
<asp:ListItem Text="Not installed" Value="" />
</asp:DropDownList>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="locationLabel" runat="server"\
Text='<%# Eval("LocationID") == null
? ""
: Eval("Location.Name") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Codebehind:
void editPrinterDetailsView_ItemUpdating( object sender,
DetailsViewUpdateEventArgs e )
{
// Use a helper method to find the dropdown inside the details view
// and get the selected value.
string locationID = ControlHelper
.GetDropDownValue( editPrinterDetailsView,
"locationDropDownList" );
if (locationID == string.Empty)
{
locationID = null;
}
if (e.NewValues.Contains( "LocationID" ))
{
e.NewValues["LocationID"] = locationID;
}
else
{
e.NewValues.Add( "LocationID", locationID );
}
e.OldValues["LocationID"] = -1;
}

Resources