C# Archives - Tech Insights Unveiling Tomorrow's Tech Today, Where Innovation Meets Insight Sun, 31 Dec 2023 07:48:03 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://i0.wp.com/reactconf.org/wp-content/uploads/2023/11/cropped-reactconf.png?fit=32%2C32&ssl=1 C# Archives - Tech Insights 32 32 230003556 C#: How to Check if a string is numeric in C# https://reactconf.org/how-to-check-if-a-string-is-numeric-in-csharp/ https://reactconf.org/how-to-check-if-a-string-is-numeric-in-csharp/#respond Wed, 27 Dec 2023 06:33:04 +0000 http://reactconf.org/?p=211 In this article, we will learn different ways to check if a string is numeric in c#. We’ll go through typical difficulties and obstacles, as well as best practices for …

The post C#: How to Check if a string is numeric in C# appeared first on Tech Insights.

]]>
In this article, we will learn different ways to check if a string is numeric in c#. We’ll go through typical difficulties and obstacles, as well as best practices for working with string and numeric data types in c#.

Create a Console Application

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new Console Application.

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “Console App” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Click the “Create” button

Use TryParse() method to check if a string is a numeric

The TrypParse() method is the simplest way to check if a string is numeric in c#. This method takes in a string and tries to parse it as an integer. If the string is a valid integer, then the method will return true and save the parsed integer value in the out parameter.

string stringvalue = "978912";
int numericvalue;
bool isNumber = int.TryParse(stringvalue, out numericvalue);
if (isNumber == true)
  {
    Console.WriteLine("String contain number");
}
else
{
    Console.WriteLine("String Not contain number");
}

Using Regular Expressions

Regular repression is extremely helpful when checking patterns within a string. And it makes pattern matching more versatile and powerful.

string stringvalue = "901287";
bool isNumber = Regex.IsMatch(stringvalue, @"^\d+$");

if (isNumber == true)
{
    Console.WriteLine("String contain number ");
}
else
{
    Console.WriteLine("String Not contain number");
}

The Regex.IsMatch method to check if the string contains only digits.

See More: Create a Login Form in React TypeScript

The post C#: How to Check if a string is numeric in C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-check-if-a-string-is-numeric-in-csharp/feed/ 0 211
Group by Multiple Columns in LINQ C# https://reactconf.org/how-to-group-by-multiple-columns-in-linq-csharp/ https://reactconf.org/how-to-group-by-multiple-columns-in-linq-csharp/#respond Wed, 22 Nov 2023 07:35:55 +0000 https://labpys.com/?p=2167 In this article, we will learn the Group y multiple Columns in LINQ C#. The ‘group by ‘method in LINQ to group data based on one or more columns. Here’s …

The post Group by Multiple Columns in LINQ C# appeared first on Tech Insights.

]]>
In this article, we will learn the Group y multiple Columns in LINQ C#. The ‘group by ‘method in LINQ to group data based on one or more columns.

Here’s an example of how to Group by multiple columns using LINQ in C#.

Create an Asp.NET Core MVC or Web API Project

Assuming you have Visual Studio 2019 or Visual Studio 2022 installed, follow these steps to create a new ASP.NET Core Project

  • Open the visual studio (IDE).
  • Click on the “Create new project” option.
  • Choose “ASP.NET Core Web Application” from the list of available templates.
  • Click the Next button.
  • The configure a new project, specify the name and location of your project.
  • Click the “Next” button.
  • Then select .Net Core as the runtime and choose the version from the dropdown list at the top.
  • Make sure to uncheck the checkboxes for “Enable Docker Support” and “Configure for HTTPS” since we won’t be using authentication.
  • Click the “Create” button

Consider an example Employee class with properties like FirstName, LastName, City, and State. We’ll group employees based on their City and State.

Create a Model

namespace WEB_API_without_EF.Models
{
    public class Employees
    {
        public int ID { get; set; }
        public string Company { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string JobTitle { get; set; }
        public string Address { get; set;}

        public string City { get; set; }

        public string state { get; set; }

    }
}

Create a Controller


namespace WEB_API_without_EF.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {

        [HttpGet("GetgroupBy")]
        public IActionResult GetgroupBy()
        {
            List<Employees> employees = new List<Employees>
            {
                new Employees{FirstName="Anna", LastName="Bedecs", Company="Company A", City="Seattle",state="WA"},
                new Employees{FirstName="Antonio", LastName="Gratacos Solsona", Company="Company B", City="Boston",state="MA"},
                new Employees{FirstName="Thomas" ,LastName="Axen", Company="Company C", City="Seattle",state="WA"},
                new Employees{FirstName="Christina", LastName="Lee", Company="Company D", City="New York",state="NY"},
                new Employees{FirstName="Martin" ,LastName="O’Donnell", Company="Company E", City="Minneapolis",state="MN"},
                new Employees{FirstName="Francisco", LastName="Pérez-Olaeta", Company="Company F", City="Milwaukee",state="WI"},

            };

            var groupemployee = from emp in employees
                                group emp by new { emp.City, emp.state } into empgroup
                                select new
                                {
                                   Name =$"City : {empgroup.Key.City} State : {empgroup.Key.state}",
                                   employees= empgroup.ToList(),
                                };
            
      

            return Ok(groupemployee);

        }
}
}

Output:

Group by Multiple Columns in LINQ C#

See More :

Upload Multiple Files in Angular with ASP.NET Core Web API

The post Group by Multiple Columns in LINQ C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-group-by-multiple-columns-in-linq-csharp/feed/ 0 2167
.NET CORS | How to Enable CORS in ASP.NET CORE WEB API https://reactconf.org/net-cors-how-to-enable-cors-in-asp-net-core-web-api/ https://reactconf.org/net-cors-how-to-enable-cors-in-asp-net-core-web-api/#respond Sat, 28 Oct 2023 07:37:36 +0000 https://labpys.com/?p=2018 What is CORS CORS stands for Cross-Origin Resource Sharing. It is an HTTP protocol that allows web applications to access resources hosted on different domains. In this article, we will …

The post .NET CORS | How to Enable CORS in ASP.NET CORE WEB API appeared first on Tech Insights.

]]>
What is CORS

CORS stands for Cross-Origin Resource Sharing. It is an HTTP protocol that allows web applications to access resources hosted on different domains. In this article, we will learn How to Enable CORS in ASP.NET Core Web API.

How to Enable CORS

Enabling CORS in ASP.NET Core Web API is quite easy, as the platform comes with built-in features to support that.

Enable CORS Policy with Specific Origin

You need to configure CORS in the Program.cs file, if you are using below .NET 6 then configure CORS in the startup.cs file.

Open the Program.cs file in your editor and modify it. Here is how to enable CORS in ASP.NET Core.

   Services.AddCors(Opt =>
       {
         Opt.AddPolicy("CorsPolicy", policy =>
        {
             policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
                 });
            });

app.UseCors("CorsPolicy");

Above code example, we are using the WithOrigins method, which accepts a list of string URIs as parameters, and allows you to specify multiple origins for a single CORS Policy.

Enable CORS Policy with any Origin

With this CORS policy, we are grating access to all origins “AllowAnyOrigin”, allowing any request header “AllowAnyHeader”, and permitting any HTTP method “AllowAnyMethod”

 Services.AddCors(Opt =>
       {
         Opt.AddPolicy("CorsPolicy", policy =>
        {
             policy.AllowAnyOrigin().
                    AllowAnyHeader().
                    AllowAnyMethod(); 
                 });
            });

app.UseCors("CorsPolicy");

CORS Policy Options

Here are the CORS policy options you can use to configure your ASP.NET Core WEB API:

  1. AllowAnyOrigin: To accept requests from any domain
  2. WithOrigins: To allow requests only from specific domains.
  3. WithMethods: to specify which HTTP methods are allowed in the request.
  4. AllowAnyMethod: To allow any HTTP method (GET, POST, PUT, etc.) in the request.
  5. AllowAnyHeader: To accept any HTTP request header.
  6. WithHeaders: To specify which HTTP headers are allowed in the request.
  7. WithExposedHeaders: To specify which headers are safe to expose to the API of a CORS API specification.
  8. AllowCredentials: To allow requests with credentials.

Conclusion

In this article, we have shown you how to enable CORS(Cross-Origin Resource Sharing) in an ASP.NET Core Web API. CORS is essential for allowing web applications hosted in different domains to access your API securely.

See More Articles:

Difference between IEnumerable and IQueryable in C#

The post .NET CORS | How to Enable CORS in ASP.NET CORE WEB API appeared first on Tech Insights.

]]>
https://reactconf.org/net-cors-how-to-enable-cors-in-asp-net-core-web-api/feed/ 0 2018
Difference between IEnumerable and IQueryable in C# https://reactconf.org/difference-between-ienumerable-iqueryable-in-csharp/ https://reactconf.org/difference-between-ienumerable-iqueryable-in-csharp/#respond Thu, 26 Oct 2023 06:22:33 +0000 https://labpys.com/?p=2002 In C#, we have often used collections Interfaces IEnumerable, and IQueryable interchangeably, but it’s very important to know the difference between each other. Each interface has its own specific characteristics, …

The post Difference between IEnumerable and IQueryable in C# appeared first on Tech Insights.

]]>
In C#, we have often used collections Interfaces IEnumerable, and IQueryable interchangeably, but it’s very important to know the difference between each other. Each interface has its own specific characteristics, that differentiate them and which make it more adaptable to certain scenarios.

Let’s explore the difference between IEnumerable, and IQueryable in C# and which interface to use in which case, let’s see.

Here are the differences between IEnumerable and IQuerable:

  • IEnumerable is an interface in the System. Collections namespace, whereas IQueryable is an interface in the System.Linq namespace.
  • IEnumerable is used for in-memory collection queries, whereas IQueryable is suitable for querying data from out-of-memory collections, such as remote databases or services.
  • IEnumerable is beneficial for LINQ to Object, while IQueryable is beneficial for LINQ to SQL.
  • Both support deferred execution, but IEnumerable does not support lazy loading, whereas IQueryable supports lazy loading.
  • IEnumerable doesn’t support custom queries, while IQueryable supports custom queries using CreateQuery and executes methods.
  • IEnumerable does not run filters on the server side. While IQueryable executes a “select query” on the server side with all filters. When querying data from a database.
  • Both can only move forward over a collection.
  • The IQueryable interface inherits from IEnumerable, so it can prefer everything that IEnumerable can do.

Summarizes the key differences between IEnumerable and IQueryable:

FeatureIEnumerableIQueryable
NamespaceSystem.CollectionsSystem.Linq
Client-sideLINQ to ObjectLINQ to SQL
LINQ typeNoYes
Lazy loading supportsNoYes
Move forwardYesYes
Query ExecutionServer-sideServer side
The difference between IEnumerable and IQueryable

See More articles:

Return an Empty Collection in C#

The post Difference between IEnumerable and IQueryable in C# appeared first on Tech Insights.

]]>
https://reactconf.org/difference-between-ienumerable-iqueryable-in-csharp/feed/ 0 2002
How to Convert Datatable to Object Model in ASP.NET Core MVC C# https://reactconf.org/how-to-convert-datatable-to-object-model-in-asp-net-core-mvc-c/ https://reactconf.org/how-to-convert-datatable-to-object-model-in-asp-net-core-mvc-c/#respond Thu, 27 Apr 2023 07:18:23 +0000 https://labpys.com/?p=1175 If you are developing an ASP.NET Core application, you may come across a situation where you need to convert Datatable to Object Model. In this article, we will learn How …

The post How to Convert Datatable to Object Model in ASP.NET Core MVC C# appeared first on Tech Insights.

]]>
If you are developing an ASP.NET Core application, you may come across a situation where you need to convert Datatable to Object Model. In this article, we will learn How to Convert Datatable to Object Model in ASP.NET Core MVC C#.

Install Required Software

  • Download NET Core SDK from here
  • Download Visual Studio or Visual Studio Code from here

What exactly is a DataTable?

A DataTable is a .NET Framework class that represents a datatable in memory. It is made up of a collection of DataRow objects, each representing a single row in the database. The table’s columns are defined using DataColumn objects.

What exactly is an Object Model?

The model is a standard C# class. The model is responsible for handling data and business logic. A model represents the data’s shape. The model is responsible for handling database-related changes.

Why Should You Convert a DataTable to an Object Model?

Converting a DataTable to an Object Model might make working with data in your application easier. When you have an Object Model, you may access data using strongly typed properties and methods, which makes your code more maintainable and error-prone.

DataTable to Object Model Conversion in C#

To represent the entity you wish to convert the DataTable to, create a class. Connect the DataTable columns to the class’s attributes. For each row in the DataTable, create an instance of the class, and fill the attributes with the information from the appropriate columns.

ASP.NET Core C#’s DataTable to Object Model Conversion

Let’s look at an example of how to do this in ASP.NET Core C# with a DataTable. Assume you have a DataTable containing a list of items, each with an Id, firstname, lastname, job, salary, and hiredate.

Create Model

namespace Asp.netcore_Tutorials.Models
{
    public class Employee
    {
        public int EmpId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string job { get; set; }
        public float amount { get; set; }
        public DateTime tdate { get; set; }
    }
}

Create Controller

using Asp.netcore_Tutorials.Models;
using Microsoft.AspNetCore.Mvc;
using System.Data;

namespace Asp.netcore_Tutorials.Controllers
{
    public class DatatabletoModelController : Controller
    {
        public IActionResult Index()
        {
            var datatable = new DataTable();

            datatable.Columns.Add("EmpId", typeof(int));
            datatable.Columns.Add("firstname",type:typeof(string));
            datatable.Columns.Add("lastname",type:typeof(string));
            datatable.Columns.Add("job", type: typeof(string));
            datatable.Columns.Add("amount", type: typeof(string));
            datatable.Columns.Add("tdate", type: typeof(DateTime));

            datatable.Rows.Add(1,"John ","Stephen","Manager","150000","10-01-2023");
            datatable.Rows.Add(1, "Vicky ", "Poiting", "Software Developer", "10000", "10-02-2022");
            datatable.Rows.Add(1, "Nathan", "Mick", "Tester", "70000", "10-11-2022");

            List<Employee> custlist = new List<Employee>();            
            custlist = (from DataRow dr in datatable.Rows
                        select new Employee()
                        {
                            EmpId = Convert.ToInt32(dr["EmpId"]),
                            FirstName = dr["firstname"].ToString(),
                            LastName = dr["lastname"].ToString(),
                            job = dr["job"].ToString(),
                            amount = Convert.ToInt64(dr["amount"]),
                            tdate = Convert.ToDateTime(dr["tdate"].ToString())
                        }).ToList();
            return View(custlist);
        }
    }
}

In this example, a class called Employee is created to represent an entity for an Employee, complete with an id, firstname,lastname, job,salary, and hiredate. Then using the same columns and some test data, we create a DataTable. The last step involves iterating through the DataTable’s rows, creating instances of the Employee class for each row, and filling each instance’s attributes with information from the appropriate columns. The Employee class instances are then each added to a list of Employees.

Previous Article Also check Populate DropdownList with Month Names Using LINQ

Create View

@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@model IEnumerable<Asp.netcore_Tutorials.Models.Employee>
@{
    ViewData["Title"] = "Home Page";
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>

<h1>DataTable to Model</h1>

<table class="table table-primary">
    <thead>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Job</th>
            <th>Salary</th>
            <th>Date</th>
        </tr>
    </thead>
    @foreach(var custdr in Model)
    {
    <tbody>
        <tr>
            <td>@custdr.EmpId</td>
            <td>@custdr.FirstName</td>
            <td>@custdr.LastName</td>
            <td>@custdr.job</td>
            <td>@custdr.amount</td>
            <td>@custdr.tdate</td>
        </tr>
       
    </tbody>
    }
</table>

Conclusion
In this article, we covered how to change an ASP.NET Core DataTable into an object model. It can be simpler to work with the data in your application and more manageable and error-free to write code by converting a DataTable to an Object Model. You should be able to convert DataTables to Object Models in your own ASP.NET Core apps by following the instructions provided in this article.

The post How to Convert Datatable to Object Model in ASP.NET Core MVC C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-convert-datatable-to-object-model-in-asp-net-core-mvc-c/feed/ 0 1175
How to Create Dynamic Menu in Asp.Net Core MVC C# https://reactconf.org/how-to-create-dynamic-menu-in-asp-net-core-mvc-c/ https://reactconf.org/how-to-create-dynamic-menu-in-asp-net-core-mvc-c/#comments Tue, 10 Jan 2023 17:38:23 +0000 https://labpys.com/?p=643 In this article, we will learn How to Create a Dynamic Menu in Asp.Net Core MVC C#. In the previous article, we discussed https://labpys.com/how-to-generate-qr-code-using-asp-net-core-c/. Prerequisites Create an ASP.NET Core MVC …

The post How to Create Dynamic Menu in Asp.Net Core MVC C# appeared first on Tech Insights.

]]>
In this article, we will learn How to Create a Dynamic Menu in Asp.Net Core MVC C#. In the previous article, we discussed https://labpys.com/how-to-generate-qr-code-using-asp-net-core-c/.

Dynamic Menu in Asp.Net Core MVC C#

Prerequisites

  • Download and install .Net Core 6.0 SDK from here
  • Download and Install Microsoft Visual Studio 2022 from here
  • Sql-Server

Create an ASP.NET Core MVC Project

Open visual studio, Go to File menu and click on New and select Project. Then new project window, select ASP.NET Core Web Application (Model-View-Controller) template.

Dynamic Menu in Asp.Net Core MVC C#

Enter  project name and click create.

Dynamic Menu in Asp.Net Core MVC C#

Install NuGet Packages

  • Microsoft Entity Framework Core Sql Server.
  • Microsoft Entity Framework Core Tools

Configure appsettings.json

There are two connection string one is SQL Server and another one is excel .

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "sqlconnection": "Server=(local)\\MSSQL;Database=InventoryDB;Trusted_Connection=True;MultipleActiveResultSets=true",   
    
  },
  "AllowedHosts": "*"
}

Create Model

Create Model class and DbContext Class.

//MenuMast.cs

using DocumentFormat.OpenXml.Presentation;
using System.ComponentModel.DataAnnotations;

namespace Asp.netcore_Tutorials.Models
{
    public class MenuMast
    {
        public MenuMast()
        {
            SubMenuMast = new HashSet<SubMenuMast>();
        }

        [Key]
        public int MenuCode { get; set; }

        [Required]
        [StringLength(250)]
        public string MenuName { get; set; }

        [StringLength(10)]
        public string DesignCodeTime { get; set; }

        public int? MenuSortOrder { get; set; }

        public virtual ICollection<SubMenuMast> SubMenuMast { get; set; }

    }
}

SubMenuMast.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Asp.netcore_Tutorials.Models
{
    public class SubMenuMast
    {
        
        [Key]
        public int SubMenuCode { get; set; }

        public int ModuleCode { get; set; }
     
        [Required]
        [StringLength(150)]
        public string SubMenuName { get; set; }

        [StringLength(150)]
        public string TableName { get; set; }

        public bool HideFlag { get; set; }

        public int? SubMenuSortOrder { get; set; }

        public int MenuCode { get; set; }
        [ForeignKey(nameof(MenuCode))]
        public virtual MenuMast MenuMasts { get; set; } 
    }
}

MenuDbcontext.cs

using Microsoft.EntityFrameworkCore;

namespace Asp.netcore_Tutorials.Models
{
    public class MenuDbcontext : DbContext 
    {
        public MenuDbcontext(DbContextOptions<MenuDbcontext> option):base(option)
        {

        }

        public virtual DbSet<MenuMast> MenuMasts { get; set; }
        public virtual DbSet<SubMenuMast> SubMenuMasts { get; set; }
   
    }
}

Create Interface and Concrete Class

Interface IMenuNavigation.cs

using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.Repository
{
    public interface IMenuNavigation
    {
        Task<IEnumerable<SubMenuMast>> MenuList();
        Task<IEnumerable<MenuMast>> MenuMastList();             
    }
}

Concrete Class MenuNavigation.cs

using Asp.netcore_Tutorials.Models;
using Microsoft.EntityFrameworkCore;
using System.Collections;

namespace Asp.netcore_Tutorials.Repository
{
    public class MenuNavigation : IMenuNavigation
    {
        private readonly MenuDbcontext _menuDbcontext;

        public MenuNavigation(MenuDbcontext menuDbcontext)
        {
            _menuDbcontext = menuDbcontext;
        }
        public async Task<IEnumerable<SubMenuMast>> MenuList()
        {
            return await _menuDbcontext.SubMenuMasts.Include(m=>m.MenuMasts).ToListAsync();
        }
        public async Task<IEnumerable<MenuMast>> MenuMastList()
        {
             return await _menuDbcontext.MenuMasts.Include(m=>m.SubMenuMast).ToListAsync();
        }
    }
}

Configure Program.cs

using Asp.netcore_Tutorials.Models;
using Asp.netcore_Tutorials.Repository;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using Microsoft.AspNetCore.Session;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

 
builder.Services.AddDbContext<MenuDbcontext>(conn => conn.UseSqlServer(builder.Configuration.GetConnectionString("sqlconnection")));
 
builder.Services.AddScoped<IMenuNavigation, MenuNavigation>();

builder.Services.AddSession();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseSession();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

Migration

Add-Migration 'Initial-Create'
Update-Database

Create View Model

menuViewModel.cs

using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.ViewModel
{
    public class menuViewModel
    {
      //  public  ICollection<SubMenuMast> menuListViewModel { get; set; }
        public IEnumerable<MenuMast> MenuList { get; set; }
    }
}

Create Controller

MenuController.cs

using Asp.netcore_Tutorials.Repository;
using Microsoft.AspNetCore.Mvc;
using Asp.netcore_Tutorials.ViewModel;
using Microsoft.AspNetCore.Mvc.Rendering;
using Asp.netcore_Tutorials.Models;

namespace Asp.netcore_Tutorials.Controllers
{
    public class MenuController : Controller
    {
        private readonly IMenuNavigation _menuList;

        public MenuController(IMenuNavigation menuList)
        {
            _menuList = menuList;
        }

        public IActionResult Index()
        {
            menuViewModel menuListViewModel = new menuViewModel();     
            menuListViewModel.MenuList =  _menuList.MenuMastList().Result.ToList();
            return View(menuListViewModel);
        }
    }
}

Customize View

index.cs

 
@model Asp.netcore_Tutorials.ViewModel.menuViewModel;
 
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <title></title>

        <!-- Bootstrap CSS CDN -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        <!-- Our Custom CSS -->
      
        <!-- Scrollbar Custom CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">

         
       <link href="~/css/style.css" rel="stylesheet" />

    </head>
    <body>
        <div class="wrapper">
            <!-- Sidebar Holder -->
            <nav id="sidebar">
                <div class="sidebar-header">
                    <h3>Dynamic Menu</h3> 
                </div>

                <ul class="list-unstyled components">
                 @foreach (var menu in Model.MenuList)
                 {
                  <li class="active">
                        <a href="#@menu.MenuName" data-toggle="collapse" aria-expanded="false" class="dropdown-toggle">@menu.MenuName</a>
                    <ul class="collapse list-unstyled" id="@menu.MenuName">
                       @if (@menu.SubMenuMast.Count > 0)
                            {
                                @foreach (var item in menu.SubMenuMast)
                                {
                                    <li><a href="@item.SubMenuName">@item.SubMenuName</a></li>
                                }; 
                            };                     
                    
                    </ul>
                    </li>
                   };
                  </ul>              
            </nav>

            <!-- Page Content Holder -->
            <div id="content">

                <nav class="navbar navbar-default">
                    <div class="container-fluid">

                        <div class="navbar-header">
                            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">
                                <i class="glyphicon glyphicon-align-left"></i>
                                <span>Toggle Sidebar</span>
                            </button>
                        </div>

                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                            <ul class="nav navbar-nav navbar-right">
                                <li><a href="#">Page</a></li>
                            </ul>
                        </div>
                    </div>
                </nav>

            
            </div>
        </div>

         <!-- jQuery CDN -->
    <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
    <!-- Bootstrap Js CDN -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <!-- jQuery Custom Scroller CDN -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
 
 
    <script type="text/javascript">
        $(document).ready(function () {

            $('#sidebarCollapse').on('click', function () {
                $('#sidebar').toggleClass('active');
            });

        });
    </script>
    </body>
</html>

 

The post How to Create Dynamic Menu in Asp.Net Core MVC C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-create-dynamic-menu-in-asp-net-core-mvc-c/feed/ 2 643
Load data into ListView from DataBase in C# https://reactconf.org/how-to-load-data-into-listview-from-database/ https://reactconf.org/how-to-load-data-into-listview-from-database/#comments Sat, 26 Apr 2014 17:50:00 +0000 http://www.sqlneed.com/2014/04/26/load-data-into-listview-from-database-in-c/ Handling vast volumes of data is becoming a normal practice in today’s digital era, and storing them in a database is a crucial part. However, getting and showing this data …

The post Load data into ListView from DataBase in C# appeared first on Tech Insights.

]]>
Handling vast volumes of data is becoming a normal practice in today’s digital era, and storing them in a database is a crucial part. However, getting and showing this data in an understandable manner might be difficult. In this post, we’ll look at how to use C# to Load data into ListView from DataBase in C#.

Understanding Listview

Before we go into the specifics of loading data into Listview from a SQL Server database, it’s important to understand what Listview is. The Listview control in C# displays data in a tabular style. It enables users to effortlessly sort, filter, and pick data. Listview is a great control for displaying big amounts of data because it has a lot of customization possibilities and is very user-friendly.

Creating a Connection to the SQL Server Database

Following the installation of the SQL Server database, the following step is to connect to it using C#. The SqlConnection class is one of the most often used techniques in C# for establishing a connection to the SQL Server database.

SqlConnection cnn = new SqlConnection("Data Source=MachineName;Initial Catalog=DatabaseName;Integrated Security=True");

Data Loading into a Listview

Following the establishment of the connection, the data from the database is loaded into a listview. The instructions below demonstrate how to load data into a listview using C#:

Create Query to Retrieve Data from SQL Server Database

String sql = "Select Employeeid, FirstName, LastName from Employees";

Create a SqlCommand Object

SqlCommand cmd=new SqlCommand(sql,cnn);

Create a SqlDataReader Object

 SqlDataReader Reader = cmd.ExecuteReader();

Load Data into Listview

while(Reader.Read())
            {
 
 ListViewItemlv = new ListViewItem(Reader.GetInt32(0).ToString());
                lv.SubItems.Add(Reader.GetString(1));
                lv.SubItems.Add(Reader.GetString(2));
                listView1.Items.Add(lv);
 
 
            }

The preceding code generates a query to obtain data from the SQL Server database, a SqlCommand object, and a SqlDataReader object to retrieve the data, and finally loads data into the listview control.

Full Source Code

usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Data.SqlClient;
 
namespaceListViewTutorial
{
    public partial class Form1 : Form
    {
       stringcon = "Data Source=MachineName;Initial Catalog=DatabaseName;Integrated Security=True";
 
        publicForm1()
        {
            InitializeComponent();
        }
 
        privatevoid Form1_Load(objectsender, EventArgs e)
        {
            listView1.GridLines = true;
            listView1.View = View.Details;
 
            //Add Column Header
 
            listView1.Columns.Add("Employee ID", 150);
            listView1.Columns.Add("First Name", 150);
            listView1.Columns.Add("Last Name", 150);
        }
 
 
        privatevoid button1_Click(objectsender, EventArgs e)
        {
            
   // Chnage sqlquery and table name
 
         stringsql = "Select Employeeid,FirstName,LastName from Employees";
            SqlConnectioncnn = new SqlConnection(con);
            cnn.Open();
            SqlCommandcmd=new SqlCommand(sql,cnn);
            SqlDataReaderReader = cmd.ExecuteReader();
 
            listView1.Items.Clear();
 
            while(Reader.Read())
            {
 
 ListViewItemlv = new ListViewItem(Reader.GetInt32(0).ToString());
                lv.SubItems.Add(Reader.GetString(1));
                lv.SubItems.Add(Reader.GetString(2));
                listView1.Items.Add(lv);
 
 
            }
 
             Reader.Close();
            cnn.Close();
 
        }
Load data into ListView from DataBase in C#

Listview Customization

Listview allows for extensive customization, such as changing the background color, font, and size, as well as adding photos to the control. You can make the listview more user-friendly by customizing it to match the theme of your application.

Conclusion

In this post, we looked at how to use C# to Load data into ListView from DataBase in C#. We’ve seen that Listview is an amazing control for displaying big amounts of data, with numerous customization possibilities. You may quickly load data from a SQL Server database into a listview control and provide a user-friendly interface to your application by following the methods outlined above.

More Related Post

How to Load Data into ListView from MySQL, Remove Special Characters in a string

FAQs

What exactly is a listview in C#?

In C#, a listview is a control that shows data in tabular format. It enables users to effortlessly sort, filter, and pick data.

What exactly is SQL Server?

SQL Server is a relational database management system. It is commonly used for data storage and retrieval.

How can I create a C# connection to a SQL Server database?

In C#, you may use the SqlConnection class to connect to a SQL Server database. You must supply the required connection string, which includes the server name, database name, username, and password.

In C#, how do I load data from a SQL Server database into a listview?

To load data from a SQL Server database into a listview control in C#, first, create a query to retrieve the data, then a SqlCommand object, then a SqlDataAdapter object, then a DataTable object to store the data, then fill the DataTable with data from the SqlDataAdapter, and finally load data from the DataTable to the listview control.

Is it possible to modify the listview control in C#?

Yes, the listview control can be customized in C#. To complement the theme of your application and make it more user-friendly, you can modify the background color, font, and size, as well as add photos to the control.

The post Load data into ListView from DataBase in C# appeared first on Tech Insights.

]]>
https://reactconf.org/how-to-load-data-into-listview-from-database/feed/ 4 2241