We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date
close icon

Fetch data through Web API and Data binding dynmically

I am new to blazor grid. I have some doubts. I have read your documentation but still I have some doubts to incorporate all aspects in one place.

Please see attached file for my coding.

I have already developed ASP.Net core web API and it returns datatable in string format along with the column structure.

Calling of Web API as follow:

HttpClient http = new HttpClient();

HttpRequestMessage httpRequestMessage = new HttpRequestMessage();

httpRequestMessage.Method = new HttpMethod("POST");

httpRequestMessage.RequestUri = new Uri("https://localhost:44332/api/GetTableData");

httpRequestMessage.Content = new StringContent(json);

JsonConvert.SerializeObject(oTblData);

httpRequestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

var response = await http.SendAsync(httpRequestMessage);


Getting API response and converting it to SQL Data table

dataTbl = JsonConvert.DeserializeObject<DataTable>(retJSON.Data.ToString().Trim());


Getting Column strucure from API response

TblStru = JsonConvert.DeserializeObject<List<SQLTblFldDef>>(retJSON.AdtData.ToString().Trim());


bindiing data table with grid as follow:

dataTbl = JsonConvert.DeserializeObject<DataTable>(retJSON.Data.ToString().Trim());

navigationManager.NavigateTo("/dashboard");

lstObj = new List<System.Dynamic.ExpandoObject>();

foreach (DataRow row in dataTbl.Rows)

{

      System.Dynamic.ExpandoObject e = new System.Dynamic.ExpandoObject();

      foreach (DataColumn col in dataTbl.Columns)

      {

             e.TryAdd(col.ColumnName, row.ItemArray[col.Ordinal]);

       }

       lstObj.Add(e);

 }


Grid data binding and Column creation as follow:

<SfGrid DataSource="@lstObj" id="Grid" AllowPaging="true" AllowMultiSorting="true" AllowExcelExport="true" RowHeight="35">

        <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true" Mode="EditMode.Normal"></GridEditSettings>

        <GridColumns>

            @foreach( var stru in TblStru )

            {

                if (stru.FldName.ToUpper() == "MSTID")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="false" Type="ColumnType.Number" Width="100px" IsPrimaryKey="true" Visible="false" />

                }

                else if (stru.DataType == "String")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.String" EditType="EditType.DefaultEdit"

                        TextAlign="TextAlign.Left" Width="100px"/>

                }

                else if (stru.DataType == "Int32")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.Number" EditType="EditType.NumericEdit"

                        TextAlign="TextAlign.Right" Width="100px" />

                }

                else if (stru.DataType == "Double")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.Number" EditType="EditType.NumericEdit"

                        TextAlign="TextAlign.Right" Width="100px" />

                }

                else if (stru.DataType == "DateTime")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.Date" EditType="EditType.DatePickerEdit"

                        TextAlign="TextAlign.Left" Width="100px" />

                }

                else if (stru.DataType == "Boolean")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.Boolean" DisplayAsCheckBox="true"

                        EditType="EditType.BooleanEdit" Width="100px" />

                }

            }

        </GridColumns>

    </SfGrid>



Now my problem is that I dont want to loop through data table and use  TryAdd clause as looping through data table each row and each column will affect the application performance. 


My problems are as under:

  1. Is there any way to assign data table directly to the data source same as Xamarin sfdatagrid. 
  2. How can I bind simple list to grid dropdown list.
  3. How can I set numeric as 99.99 or 999.999 or 99999 for numeric column dynamically.

All above things should be dynamically.



 







Attachment: Blazor_69096324.zip

8 Replies 1 reply marked as answer

BL Balamurugan Lakshmanan Syncfusion Team April 25, 2023 05:44 AM UTC

Hi Amish,


Greeting from Syncfusion support.


Query-1 : "Is there any way to assign data table directly to the data source same as Xamarin sfdatagrid. "


From your query, it seems straightforward to bind data to the DataGrid from a datatable. Unfortunately, we don't currently offer this feature. However, we have found a solution to meet your requirements by converting the datatable to an List<T> before binding it to SfGrid component. If the T is not known, then we have provided support for ExpandoObject or DynamicObject list. We have attached a sample for your reference, and we hope this solution meets your needs.

Reference:  Data Binding in Blazor DataGrid Component | Syncfusion

Data Binding in Blazor DataGrid Component | Syncfusion

https://www.syncfusion.com/forums/146109/binding-datatables-to-grids-a-solution?reply=NGIOCr



Query-2 : "How can I bind simple list to grid dropdown list."


You can provide custom data source and enable filter option for DropDownList while performing DataGrid editing by using the Edit params property.While setting new data source for DropDownList using Edit params, you must also specify a new Query property for DropDownList. Kindly refer the below documentation for your reference.


https://blazor.syncfusion.com/documentation/datagrid/how-to/provide-custom-data-source-and-enable-filter-option-for-drop-down-list


Query-3 :"How can I set numeric as 99.99 or 999.999 or 99999 for numeric column dynamically."


The number or integer values can be formatted using the following format strings. We have attached an UG documentation for your reference. Kindly refer the below mentioned documentation for your reference.

https://blazor.syncfusion.com/documentation/datagrid/columns#number-formatting


Please get back to us if you have further queries.


Regards,

Bala.



AM Amish replied to Balamurugan Lakshmanan April 25, 2023 10:17 AM UTC

Query 2: 

your suggested solution already I have tried before raising this query.

I don't have any model to bind with dropdown column. I want to bind string list irreespective of any model.



NP Naveen Palanivel Syncfusion Team April 26, 2023 09:44 AM UTC

Hi Amish,


Based on your query, it appears that you may not have a model class for the dropdown column. We would like to inform you that you can bind the dropdown data source using a list of strings. Please refer to the following code snippet for reference

public List<Orders> GridData { get; set; } = new List<Orders>();

    public List<string> Countries = new List<string>() { "United States", "Australia" };

    public List<string> States = new List<string>() { "New York", "Virginia", "Washington", "Queensland", "Tasmania", "Victoria" };

    public bool Enabled = false;

 


If we misunderstood your query kindly get back to us.

Regards,

Naveen Palanivel



AM Amish April 29, 2023 12:07 PM UTC

I am facing problem in grid dropdown list.

I am facing error while uploading so I am attaching link to download video.

https://1drv.ms/u/s!AujplcNrARq1hcogb5goc7Jz7qxafA

I am also pasting my code

<SfGrid DataSource="@lstObj" id="Grid" AllowPaging="true" AllowMultiSorting="true" AllowExcelExport="true" RowHeight="25" >

        <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true" Mode="EditMode.Normal" ></GridEditSettings>

        <GridColumns>

            @foreach( var stru in TblStru )

            {

                if (stru.FldName.ToUpper() == "MSTID")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="false" Type="ColumnType.Number" Width="100px" IsPrimaryKey="true" Visible="false"/>

                }

                else if (stru.DataType == "String")

                {

                    if (stru.FldName == "ModType")

                    {



                        <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" EditType="EditType.DropDownEdit" Width="120" >

                            <EditTemplate>

                                <SfComboBox ID=@stru.FldName TItem="ModType" TValue="string" DataSource="@modTypes">

                                    <ComboBoxFieldSettings Value="Id" Text="Name"></ComboBoxFieldSettings>

                                </SfComboBox>

                            </EditTemplate>

                        </GridColumn>

                    }

                    else

                    {

                        <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.String" EditType="EditType.DefaultEdit"

                            TextAlign="TextAlign.Left" Width="100px"/>

                    }

                    @*<GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.String" EditType="EditType.DefaultEdit"

                        TextAlign="TextAlign.Left" Width="100px" />*@

                }

                else if (stru.DataType == "Int32")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.Number" EditType="EditType.NumericEdit"

                        TextAlign="TextAlign.Right" Width="100px" />

                }

                else if (stru.DataType == "Double")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.Number" EditType="EditType.NumericEdit"

                        TextAlign="TextAlign.Right" Width="100px" />

                }

                else if (stru.DataType == "DateTime")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.Date" EditType="EditType.DatePickerEdit"

                        TextAlign="TextAlign.Left" Width="100px" />

                }

                else if (stru.DataType == "Boolean")

                {

                    <GridColumn Field=@stru.FldName HeaderText=@stru.FldName AllowEditing="true" Type="ColumnType.Boolean" DisplayAsCheckBox="true"

                        EditType="EditType.BooleanEdit" Width="100px" />

                }

            }

         </GridColumns>

    </SfGrid>

-------------

public List<System.Dynamic.ExpandoObject>? lstObj;


    public DataTable? dataTbl = new DataTable();


    public List<SQLTblFldDef> TblStru = new List<SQLTblFldDef>();

 public class ModType

    {

        public string Name { get; set; }

        public string Id { get; set; }

    }

    public static List<ModType> modTypes = new List<ModType>

    {

         new ModType(){ Id ="1", Name="Master"},

         new ModType(){ Id ="2", Name="Transaction"},

         new ModType(){ Id ="3", Name="Report"},

         new ModType(){ Id ="4", Name="Utility"}

    };


TblStru = JsonConvert.DeserializeObject<List<SQLTblFldDef>>(retJSON.AdtData.ToString().Trim());


                dataTbl = JsonConvert.DeserializeObject<DataTable>(retJSON.Data.ToString().Trim());

                //navigationManager.NavigateTo("/dashboard");

                lstObj = new List<System.Dynamic.ExpandoObject>();

                foreach (DataRow row in dataTbl.Rows)

                {

                    System.Dynamic.ExpandoObject e = new System.Dynamic.ExpandoObject();

                    foreach (DataColumn col in dataTbl.Columns)

                    {

                        e.TryAdd(col.ColumnName, row.ItemArray[col.Ordinal]);

                    }

                    lstObj.Add(e);

                }

here I have no predefinded model. Please check and help resolving the problem.



NP Naveen Palanivel Syncfusion Team May 8, 2023 02:00 PM UTC

Hi Amish,

From your query we understand that you are facing issue while saving the value from dropdown into the Grid data. We suggest you to overcome the problem using OnActionBegin event of Grid and  event of comboBox control to overcome the reported issue. Refer the  below code example and sample for your reference.  

 

                if (item.Key == "customerName")

                {

                    <GridColumn Field="@item.Key" AllowEditing="true" EditType="EditType.DropDownEdit">

                        <EditTemplate>

 

                            <SfComboBox ID=@item.Key TItem="ModType" TValue="string" Value="@((string)(context as IDictionary<string, object>)["customerName"])" DataSource="@modTypes">

 

                                <ComboBoxFieldSettings Value="Name" Text="Name"></ComboBoxFieldSettings>

                                <ComboBoxEvents TItem="ModType" TValue="string" ValueChange="@ValueChangeHandler"></ComboBoxEvents>

                            </SfComboBox>

 

                        </EditTemplate>

 

                    </GridColumn>

                }

                else

                {

                    <GridColumn Field="@item.Key" IsPrimaryKey="@(item.Key == "OrderID")"></GridColumn>

                }

 

            }

        }

    </GridColumns>

</SfGrid>

 

@code {

    public List<ExpandoObject> GridData { get; set; } = new List<ExpandoObject>();

    private List<string> ToolbarItems = new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" };

    public string TextValue { get; set; } = "";

    private void ValueChangeHandler(ChangeEventArgs<string, ModType> args)

    {

        TextValue = args.Value;

    }

 

 

 

    public void ActionBeginHandler(ActionEventArgs<ExpandoObject> Args)

    {

        if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Save)

        {

            var data = Args.Data as IDictionary<string, object>;

            data["customerName"] = TextValue;

        }

    }




Please let us know if you have any concerns.


Regards,

Naveen Palanivel


Attachment: Blazor_24_c4ae50b.zip

Marked as answer

AM Amish replied to Naveen Palanivel August 9, 2023 05:14 AM UTC

In all your example you are using fix class model and binding dropdownlist with column.


But in my case, I have no fixed model. I am using expandoObject as datagrid souce. 




AM Amish August 9, 2023 05:31 AM UTC

Sorry, 


Problem solved as suggested in last reply.


Thanking you. 



NP Naveen Palanivel Syncfusion Team August 10, 2023 10:59 AM UTC

Hi Amish,


Welcome


We are glad to hear that your query has been resolved.


Please get back to us if you need further assistance.


Regards,

Naveen Palanivel.


Loader.
Live Chat Icon For mobile
Up arrow icon