Monday, February 27, 2012

Using LINQ to order an ASP.NET DropDownList

How LINQ can you save you from writing many lines of code. Easy stuff:

protected void SortDropDownList(DropDownList ddlToSort)
{
    ddlToSort.DataSource = ddlToSort.Items.Cast<ListItem>()
                            .OrderBy(o => o.Text)
                            .ToList();
    ddlToSort.DataBind();
}

Wednesday, February 22, 2012

Passing on ViewState Items onto ObjectDataSource

Because the datasource instance does not run in your page instance, you will not be able to fetch your ViewState items. The only way to do this is to pass it on to the parameters. Suppose you've got a gridview, using an object data source instance called 'odsBand' and you would like to retrieve a DataSet from your db filtered by band name. In this case you need to define a electParameter which will hold the band name retrieved from your ViewState. See markup below

<asp:ObjectDataSource ID="odsBands" runat="server" 
    SelectMethod="SelectBands" 
    OnSelecting="odsBands_Selecting"
    OnSelected="odsBands_Selected"
    OnFiltering="odsBands_Filtering"
    &lt;SelectParameters>
        <asp:Parameter Name="BandName" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>

Here I set up the BandName property which will chuck the request band name string into the ViewState:

private string BandName
{
    get
    {
        return ViewState["BandName"] == null ? "" : ((string)ViewState["BandName"]);
    }
    set
    {
        ViewState["BandName"] = value;
    }
}

In the Page_Load method, I'm putting the QueryString into the Viewstate, using the BandName property:

protected void Page_Load(object sender, EventArgs e)
{
    odsBands.TypeName = this.GetType().AssemblyQualifiedName;
    
    if (!Page.IsPostBack)
    {
        BandName = Request.QueryString["bandName"];
        // This is my SPGridView instance which will display the data
        grdBand.DataSourceID = "odsBands";
    }
}

Ok cool. From here I use the property to set the input parameter 'BandName' like this:

protected void odsBands_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
    e.InputParameters["BandName"] = BandName;
}

Finally, I define the SelectMethod 'SelectBands' with one string argument which is the input parameter. In this particular case I'm using a DataSet from which I then create a DataView to filter on the parameter value:

public DataView SelectBands(string bandName)
{
    // The method below fetches the data from a db, replace this with your own source
    DataSet dsBands = BandsResourceManagement.Instance.GetBands();
    
    // BandName is also the field name in the table and I'm sorting the records by the field BandId
    DataView dvBand = new DataView(dsBands.Tables[0],"BandName = '" + bandName + "', "BandId", DataViewRowState.CurrentRows);
}