EDUDOTNET

Friday, April 28, 2017

How to convert and bind JSON string in to asp.net GridView with c# without help of looping and object mapper class (wrapper)?



How to convert and bind JSON string in to asp.net GridView with c# without help of looping and object mapper class (wrapper)?
Requirement: - If we don`t know about json string/object, how many columns are there and no any idea of column name, In this case we can`t able to create a c# class for object deserializeObject, I mean wrapper class. Here requirement is bind gridview from json object without ajax/jquery and looping in c# and without wrapper class.

1.       Create a web application in visual studio


2.        Right click on project and add a web form by click on "Web Form".


3.        After that open a windows popup in this enter your Web Form name and click on "Add" button.





4.        Open your web form .aspx source/design part and go to ToolBox and drag & drop asp.net gridview control in to web form and set gridview style as per your requirement.





5.        Here way to bind gridview from JSON following:
a.        Using dynamic keyword with JsonConvert.DeserializeObject, here you need to import Newtonsoft.Json
b.      Using DataTable with JsonConvert.DeserializeObject, here you need to import using System.Data;




Dynamic:
This is a data type, dynamic data type introduced since .Net Framework 4.0. The dynamic data type allows you to perform any operations and will be resolved at run time. It does not require explicit type casting for any operation at run-time, because it identifies the types at run-time only. Dynamic type can be passed as function argument and function also can return object type. Useful when coding using reflection or dynamic language support or with the COM objects, because we require to write less amount of code. [http://www.c-sharpcorner.com/blogs/variable-object-and-dynamic-data-type-in-c-sharp1]

DataTable:
In .NET, it's a class that represents a table of in-memory data.
 


CODE
.ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="BindJosn2Grid.aspx.cs" Inherits="BindJSON2ASPDOTGridView.BindJosn2Grid" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Bind GridView From JSON Object (Converted In to Dynamic Object [dynamic keyword])</h2>
        <asp:GridView ID="grdJSON2Grid" runat="server" BackColor="White" BorderColor="#3399ff"
            BorderStyle="Dotted" BorderWidth="1px" CellPadding="3" GridLines="Both"></asp:GridView>

        <br />
        <br />
         <h2>Bind GridView From JSON Object (Converted In to DataTable Object [DataTable])</h2>
        <asp:GridView ID="grdJSON2Grid2" runat="server" BackColor="White" BorderColor="#3399ff"
            BorderStyle="Dotted" BorderWidth="1px" CellPadding="3" GridLines="Both"></asp:GridView>
    </div>
    </form>
</body>
</html>


.CS
protected void Page_Load(object sender, EventArgs e)
        {
            //Random json string, No fix number of columns or rows and no fix column name.
            string myDynamicJSON = "[{'Member ID':'00012','First Name':'Vicki','Last Name':'Jordan','Registered Email':'vicki.j @tacinc.com.au','Mobile':'03 6332 3800','MailSuburb':'','MailState':'','MailPostcode':'','Engagement':'attended an APNA event in the past and ventured onto our online education portal APNA Online Learning','Group':'Non-member'},{'Member ID':'15072','First Name':'Vicki','Last Name':'Jordan','Registered Email':'vicki.j @tacinc.com.au','Mobile':'03 6332 3800','MailSuburb':'','MailState':'','MailPostcode':'','Engagement':'attended an APNA event in the past and ventured onto our online education portal APNA Online Learning','Group':'Non-member'}]";

            //Using dynamic keyword with JsonConvert.DeserializeObject, here you need to import Newtonsoft.Json
            dynamic myObject = JsonConvert.DeserializeObject(myDynamicJSON);
           
            //Binding gridview from dynamic object
            grdJSON2Grid.DataSource = myObject;
            grdJSON2Grid.DataBind();

            //Using DataTable with JsonConvert.DeserializeObject, here you need to import using System.Data;
            DataTable myObjectDT = JsonConvert.DeserializeObject<DataTable>(myDynamicJSON);

            //Binding gridview from dynamic object
            grdJSON2Grid2.DataSource = myObjectDT;
            grdJSON2Grid2.DataBind();
       
        }




Thursday, April 27, 2017

How to create and add a Radio List Button in to window application c#?



How to create and add a Radio List Button in to window application c#?

- As per R & D and in namespace System.Windows.Forms  there no any radio list button control. Currently windows form only RadioButton control available. Another way to create group and list of radio buttons using two windows form container like eg. GroupBox and Panel. All radio buttons we can add inside the group in windows form.
We can create our own custome radio list button using following steps:

1.       1 Create Window Application

 

2.        2. Update Form name and text as per understanding


3.        3. Right click on project and go to "Add" => click on "Component" after that appear a window


4.        4. In this window select "Component" and write your component/control name and click on "Add" button.



5.        5. After creating component display a window of component with option link "Toolbox" and View the code. For creating methods and events for our component, we need to click on "switch to code view", here we can able to right code as per requirement.


We are creating a component for RadioListButton, for it we need to update .cs file with namespace and import required namespaces...
                1. Class: RadioListButton.CS
                2. Namespace: By default project name as a namespace => namespace RadioListButton {}
                3. By default class name and inherit class public partial class RadioListButton : Component{}
                a) Change namespace for it namespace RadioListButton => namespace System.Windows.Forms              b) Remove Component class as inherit and add/inherit ListBox
                public partial class RadioListButton : Component =>  public partial class RadioListButton : ListBox
After that copy and paste all methods and events code for RadioListButton.

6.     6. Build your project
7.     7. After build your project, you can see your component inside the toolbox under your project name with component eg. RadioListButton Components




8.      8. This component we can use in our project in any form wherever we required by using drag & drop. After that we can bind the data with these controls.



Code:

frmRadioListButton.CS [Form]
namespace RadioListButton
{
    public partial class frmRadioListButton : Form
    {
        public frmRadioListButton()
        {
            InitializeComponent();

            var myCountryList = new[] { new { Id = 1, Name = "India" }, new { Id = 2, Name = "Canada" }, new { Id = 2, Name = "USA" }, new { Id = 2, Name = "Singapore" } }.ToList();

            RadioListButton.DataSource = myCountryList;
            RadioListButton.DisplayMember = "Name";
            RadioListButton.ValueMember = "Id";
        }
    }
}


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

 
RadioListButton.CS [Component]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms.VisualStyles;

namespace System.Windows.Forms
{
    public partial class RadioListButton : ListBox
    {
        Size s;
        public RadioListButton()
        {
            this.DrawMode = DrawMode.OwnerDrawFixed;
            using (var g = Graphics.FromHwnd(IntPtr.Zero))
                s = RadioButtonRenderer.GetGlyphSize(
                    Graphics.FromHwnd(IntPtr.Zero), RadioButtonState.CheckedNormal);
        }

        protected override void OnDrawItem(DrawItemEventArgs e)
        {

            var text = (Items.Count > 0) ? GetItemText(Items[e.Index]) : Name;
            Rectangle r = e.Bounds; Point p;
            var flags = TextFormatFlags.Default | TextFormatFlags.NoPrefix;
            var selected = (e.State & DrawItemState.Selected) == DrawItemState.Selected;
            var state = selected ?
                (Enabled ? RadioButtonState.CheckedNormal :
                           RadioButtonState.CheckedDisabled) :
                (Enabled ? RadioButtonState.UncheckedNormal :
                           RadioButtonState.UncheckedDisabled);
            if (RightToLeft == System.Windows.Forms.RightToLeft.Yes)
            {
                p = new Point(r.Right - r.Height + (ItemHeight - s.Width) / 2,
                    r.Top + (ItemHeight - s.Height) / 2);
                r = new Rectangle(r.Left, r.Top, r.Width - r.Height, r.Height);
                flags |= TextFormatFlags.RightToLeft | TextFormatFlags.Right;
            }
            else
            {
                p = new Point(r.Left + (ItemHeight - s.Width) / 2,
                r.Top + (ItemHeight - s.Height) / 2);
                r = new Rectangle(r.Left + r.Height, r.Top, r.Width - r.Height, r.Height);
            }
            var bc = selected ? (Enabled ? SystemColors.Highlight :
                SystemColors.InactiveBorder) : BackColor;
            var fc = selected ? (Enabled ? SystemColors.HighlightText :
                SystemColors.GrayText) : ForeColor;
            using (var b = new SolidBrush(bc))
                e.Graphics.FillRectangle(b, e.Bounds);
            RadioButtonRenderer.DrawRadioButton(e.Graphics, p, state);
            TextRenderer.DrawText(e.Graphics, text, Font, r, fc, bc, flags);
            e.DrawFocusRectangle();
            base.OnDrawItem(e);
        }


        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override SelectionMode SelectionMode
        {
            get { return System.Windows.Forms.SelectionMode.One; }
            set { }
        }

        [Browsable(false), EditorBrowsable(EditorBrowsableState.Never),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override int ItemHeight
        {
            get { return (this.Font.Height + 2); }
            set { }
        }

        [EditorBrowsable(EditorBrowsableState.Never), Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override DrawMode DrawMode
        {
            get { return base.DrawMode; }
            set { base.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; }
        }
    }
}