-->

Friday, April 29, 2016

Similar to TextChanged Event in ASP.NET MVC

This is very good article for web form users who want to get value on TextChanged Event. I mean to say that  TextChanged Event occurs when we move one textbox to another using "Tab" key. When, Web form users moves to MVC projects. He/ She faces some problems in logics. Because, in MVC, For each request we must to call controller. I have an idea to remove such task. I prefer JQuery. So first to Add a ViewModel Class into your project. You can take this sample.

1. Add a new Folder in your project, name of the folder is "viewModel". Now, add a class, which name as addition like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication27.viewModel
{
    public class addition
    {
        public int FirstNumer { get; set; }
        public int SecondNumber { get; set; }
        public int result { get; set; }
    }
}

In this we have three public property.Now, Add a controller class in Controller folder. Like that.

using System.Web.Mvc;

namespace WebApplication27.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            return View();
        }
    }
}

Add View, By using Right click on Action method name. In View section, i will add code of JQuery. You can see

@model WebApplication27.viewModel.addition

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
@using(Html.BeginForm())
{
    @Html.TextBoxFor(m=>Model.FirstNumer)
    @Html.TextBoxFor(m=>Model.SecondNumber)
    @Html.TextBoxFor(m => Model.result)
}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
    $(function () {
        $("#SecondNumber").blur(function () {
            $("#result").val(parseInt($("#FirstNumer").val()) + parseInt($("#SecondNumber").val()))
        });
    })
</script>

Wednesday, April 27, 2016

Bind ComboBox with Enum Type in WPF


In this article i will show you, How to Bind ComboBox with Enum properties.  Enum is a type, which is used to fix no of values like Sunday, Monday, Tuesday...etc.). By using XAML, you can add static resources for enumeration. In WPF We have a ObjectDataProvider for enumeration. Lets check the code.

XAML Code :

<Window x:Class="WpfApplication1212.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local1="clr-namespace:WpfApplication1212"
        xmlns:codeg="clr-namespace:System;assembly=mscorlib"
        Title="Window2" Height="300" Width="300">
    <Window.Resources>
        <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type codeg:Enum}" x:Key="myenu">
            <ObjectDataProvider.MethodParameters>
                <x:Type Type="local1:week1" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>
        <ComboBox ItemsSource="{Binding Source={StaticResource myenu}}" />
    </Grid>
</Window>

Enumeration code 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1212
{
    class Order
    {
    }
    public enum week1
    {
        sun,mon,tue,wed,
    }
}

Thursday, April 21, 2016

WPF: How to take image and button control in WPF ListView

Good Morning: Today i will teach you how to add controls in ListView. In this article i will add button control and image control. According to my previous article image control bind with source, so  it required source for binding, so i have create a ImageSource public property in class. We know that ListView contain only single view i.e GridView. A GridView contain rows and column , also we can say that cell is a combination of rows and column. In this article i have create CellTemplate.  Inside the CellTemplate we have a Data Template. In the Code behind page, we have a class with one property i.e "ImageSource", which is used for Image binding. Add a list control with class type, in it we have two images. Lets check the code and their output
XAML Code
<Window x:Class="WpfApplication11.ImageinListview"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ImageinListview" Height="300" Width="300">
    <Grid>
        <ListView Name="List1" MouseDoubleClick="getSelectedItem">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Action">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Button Content="Click Me" Click="Button_Click"/>                              
                            </DataTemplate>                        
                           
                        </GridViewColumn.CellTemplate>                      
                    </GridViewColumn>
                    <GridViewColumn Header="Image">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <Image Source="{Binding ImageSource}" Width="100" Height="100"/>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>

                    </GridViewColumn>

                </GridView>
            </ListView.View>        
           
        </ListView>
       
    </Grid>
</Window>

Code Behind Code:

using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;

namespace WpfApplication11
{
    /// <summary>
    /// Interaction logic for ImageinListview.xaml
    /// </summary>
    public partial class ImageinListview : Window
    {
        public ImageinListview()
        {
            InitializeComponent();
            bindlist();
        }

        private void bindlist()
        {
           // throw new NotImplementedException();
            List<imgs> listr = new List<imgs>();
            listr.Add(new imgs() { ImageSource = "/imag/11.png" });
            listr.Add(new imgs() { ImageSource = "/imag/bleaching.jpg" });
            List1.ItemsSource = listr;


        }
        private void getSelectedItem(object sender, MouseButtonEventArgs e)
        {
            imgs imgh = List1.SelectedItems[0] as imgs;
            MessageBox.Show(imgh.ImageSource);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
    
        }
    }
    public class imgs
    {
        public string ImageSource { get; set; }
    }
}
Code generate the following output

WPF: How to take image and button control in WPF ListView


Monday, April 18, 2016

Design ASP.NET MVC form using ViewModel class

Welcome, user. Today i would like to share something about Forms and their control like TextBox, Label, DropdownList(SelectListItem), Radio Button etc in ASP.NET MVC. Before going to details, first to share something about ViewModel.
 A ViewModel is a temporary class file which is used to store data values in properties.   
First to take fields which are used in form like UserName, Password, Email, Gender, religions etc. Because we will need controls for each fields. Lets take an simple example. Create a new MVC project.

  1. Right click on your project, Add a new Directory which name should have ViewModel
  2. Add this class file inside the ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MvcApplication1.ViewModel
{
    public class FormVM
    {
        public int Id { get; set; }
        public String UserName { get; set; }
        public String Password { get; set; }
        public String Gender { get; set; }
        public String Religion { get; set; }
        public String Image { get; set; }

        
        public bool IsSubmitted { get; set; }

    }
}

According to the ViewModel class we will take Two TextBox for UserName and Password, Three radio button for Religion, one file control for Image, one DropdownList for Gender and last One Submit control.After add this file, come to controller part. Add a new controller like this.

using MvcApplication1.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class TutorialController : Controller
    {
       public ActionResult AddUser()
        {
            FormVM viewModel = new FormVM();
            viewModel.IsSubmitted = false;
            return View(viewModel);
        }

        [HttpPost]
        public ActionResult AddUser(FormVM model, HttpPostedFileBase file)
        {
            model.IsSubmitted = true;
            if (file != null)
            {
                string pic = System.IO.Path.GetFileName(file.FileName);
                model.Image = pic;
            }
            ViewBag.Values = model.UserName + ", " + model.Password + ", " + model.Gender + ", " + model.Religion + ", " + model.Image;
            return View(model);
        }

    }
}

By above mentioned code AddUser( ) method return a ViewModel class. Also set IsSubmitted property to false. So using ViewModel class you can create a model control into your view class. So i have a view class for you where your control designed. Let see.

@model MvcApplication1.ViewModel.FormVM

@{
    ViewBag.Title = "AddUser";
    List<SelectListItem> listItems = new List<SelectListItem>();
    listItems.Add(new SelectListItem
    {
        Text = "Male",
        Value = "Male",
        Selected = true
    });
    listItems.Add(new SelectListItem
    {
        Text = "Female",
        Value = "Female"
    });
    listItems.Add(new SelectListItem
    {
        Text = "None",
        Value = "None"
    });
}



<h2>AddUser</h2>

@using (Html.BeginForm("AddUser","Tutorial",FormMethod.Post, new { enctype = "multipart/form-data" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>FormVM</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.UserName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.UserName)
            @Html.ValidationMessageFor(model => model.UserName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.PasswordFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
        <div class="editor-field">
           @Html.DropDownListFor(model => model.Gender, listItems, "  Select Gender  ")
        </div>
        <br />
        <div class="editor-label">
            @Html.LabelFor(model => model.Religion)
        </div>
        <br />
        <div class="editor-field">
            @Html.RadioButtonFor(model => model.Religion, "Hindu", new { id = "rbHindu" })
            @Html.Label("Hindu")
            @Html.RadioButtonFor(model => model.Religion, "Muslim", new { id = "rbMuslim" })
            @Html.Label("Muslim")
            @Html.RadioButtonFor(model => model.Religion, "Other", new { id = "rbOther" })
            @Html.Label("Other")
        </div>
        <br/>
        <div class="editor-label">
            @Html.LabelFor(model => model.Image)
        </div>
        <div class="editor-field">
            <input type="file" name="file" id="file" style="width: 100%;" />
            
        </div>

        <p>
            <input type="submit" value="Submit" />
        </p>
    </fieldset>
}

<div>
    @if(Model.IsSubmitted){
        <p>@ViewBag.Values</p>
    }
</div>

Crate form control according to above mentioned code. When we click on Submit button then value of all control will display on paragraph using ViewBag variable. Now code generate the following output:

Design ASP.NET MVC form using ViewModel class

Saturday, April 16, 2016

Find some of Html Table column using JQuery

In this article i will show you how to find sum of single column of a html Table. We all know that a table contain table row and table column. Each row and column contains a cell. in this article i will use Id of the cell. We all know that id of the cell is different from other cell so we arrange id with numerical no like first cell id is amtlbl_0 and further is amtlbl_1, amtlbl_2. by using each method we can get the all ids. So the main logic is get the id which contain text like "amtlbl". In Jquery we have some technique to get the approximate id by using


 $("[id*=amtlbl]")
Check the complete source code: 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript">

        $(function () {
            var grandtotal = 0;
            $("[id*=amtlbl]").each(function () {
                grandtotal = grandtotal + parseFloat($(this).html());


            })
            $("[id*=totlbl]").html(grandtotal.toString());

        });

        </script>
</head>
<body>
    <table style="width:100%;">
    <tr><td>Id</td><td>Amount</td><td>City</td></tr>
    <tr><td>1</td><td id="amtlbl_0">200</td><td>Pilani</td></tr>
    <tr><td>2</td><td id="amtlbl_1">800</td><td>Jaipur</td></tr>
    </table>
    <label id="totlbl"/>
</body>
</html>

Code generate the following output:


Find some of Html Table column using JQuery

BackgroundWorker Example in WPF C#

Background Worker is used to do processing in background.  I mean to say that if you have two work and you want to do complete both task at same time then must to use BackgroundWorker class. You can do two task at same time , like in gmail, attach a file with writing some text in the Text. Use this example and see more things about BackgroundWorker class.


XAML Code: 

<Grid>
        <Button Content="Run BackGround Work" HorizontalAlignment="Left" Margin="38,32,0,0" VerticalAlignment="Top" Width="209" Click="Button_Click"/>

        <Label Content="" HorizontalAlignment="Left" Margin="38,68,0,0" VerticalAlignment="Top" Name="processlbl"/>

        <Label Content="" HorizontalAlignment="Left" Margin="217,68,0,0" VerticalAlignment="Top" Name="Completelbl"/>

        <Button Content="Other Task" HorizontalAlignment="Left" Margin="48,157,0,0" VerticalAlignment="Top" Width="199" Click="Button_Click_1"/>

        <TextBox Name="t1" HorizontalAlignment="Left" Height="23" Margin="48,198,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="199"/>

        <Label Content="" HorizontalAlignment="Left" Margin="60,226,0,0" VerticalAlignment="Top" Name="outputlbl"/>

    </Grid>

Code Behind Code:

using System.ComponentModel;
using System.Windows;

namespace WpfApplication11
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        BackgroundWorker worker = new BackgroundWorker();
        public MainWindow()
        {
            InitializeComponent();
            worker.DoWork += worker_Dowork;
            worker.RunWorkerCompleted += worker_RunworkerCompleted;
        }

        private void worker_RunworkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                Completelbl.Content = "Complete Backgroung Work";
            }
            else
            {
                Completelbl.Content = "Fail";
            }
        }
        private delegate void mydelegate(int i);
        private void displayi(int i)
        {
            processlbl.Content = "Background work:" + i.ToString();
        }
        private void worker_Dowork(object sender, DoWorkEventArgs e)
        {
            for (int i = 0; i < 20; i++)
            {
                System.Threading.Thread.Sleep(2000);
                if(worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                mydelegate deli = new mydelegate(displayi);
                processlbl.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, deli, i);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            worker.RunWorkerAsync();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            outputlbl.Content = t1.Text;
        }
    }
}

Friday, April 15, 2016

Windows Forms Methods

Windows Forms methods enable you to perform various tasks, such as opening, activating and closing the form.

The commonly used methods are explained in the following:
1. Show ( ) 
Description : Is used to display a form.
Example: Form2 frmobj = new Form2();
frmobj.Show();

Explanation : This code creates a new instance of the Form2 form by using the new keyword. The Show() method display the instance of Form2 form.

2. Hide( )
Description: Is used to hide a form.
Example: Form1 frmobj = new Form1();
frmobj.Hide();
//you can use
this.Hide( ); // for current Form1

Explanation: This code creates a new instance of the Form1 form by using the new keyword. The Hide() method hides the instance of Form1 form.

3. Activate ( )
Description: Is used to activate a form and set the focus on it. When you use this method. It brings the form to the front(if it is the current application) or flashes the form caption(if it is not the current application) on the task bar.
Example: Form1 frmobj = new Form1();
frmobj.Activate();
Explanation : This code sets focus on a form named Form1.

4. Close ( )
Description: Is used to close a form.
Example: Form1 frmobj = new Form1();
frmobj.Close();
Explanation: This code closes the form named Form1.

5. SetDesktopLocation()
Description: Is used to set the desktop location of a form at runtime. This method takes the X and Y coordinates of the desktop as its parameters.
Example: Form1 frmobj = new Form1();
frmobj.SetDesktopLocation(200,200);
Explanation : This code displays the form named Form1 at the specified location.

Thursday, April 7, 2016

Types of Dialog Boxes in Windows Form C#

Windows provides the following type of dialog boxes:
1. Modal
2. System Modal
3. Modeless

Modal Dialog Box : A modal dialog box does not allow you to switch focus to another area of the application, which has invokes the dialog box. However, you can switch to other windows application while the modal dialog box is being displayed on the screen.
For example, the Save as dialog box of Microsoft word is a modal dialog box. If you are trying to save a word file by using the Save As dialog box, you cannot make any changes in the word document until it is saved. The following figure shows the save as dialog box.


Modal Dialog Box


System Modal Dialog Box
The System modal dialog box takes control of the entire Windows environment. For example, the Windows Log On dialog box is a system modal dialog box.
The following figure displays the Log On to Windows dialog box.
Sometimes, error messages are displayed by using a system modal dialog box. When such messages appear on the screen, the user is not allowed to switch to, or interact with, any other Windows application until the system modal dialog box is closed.

System Modal Dialog Box


Modeless Dialog Box

Types of Dialog Boxes in Windows Form C#

The modeless dialog box stays on the screen and is available for use at any time. For example, the Find and Replace dialog box of Microsoft Word is a modeless dialog box. This modeless dialog box allows you to switch to another area of the application, which has invoked the dialog box, or to another windows application.

Tuesday, April 5, 2016

How to show image from database table in ASP.NET MVC

In this article i will show you, How to display image from database in ASP.NET MVC. To do this task, we will use <img /> tag in view section. First of all, Create a connection with the database using Entity Data model (Learn How to use ADO.NET Entity Data Model). In the controller action method pass the list of data to the view. Like that:

 
 private DatabaseEntities db = new DatabaseEntities();

        // GET: Home
        public ActionResult Index()
        {
            return View(db.Employees.ToList());
        }

In the View section: 

@model IEnumerable<WebApplication23.Employee>

@foreach (Employee item in Model)
{
<img src="@Url.Content(item.Database_Picture_column)" width="100" height="100" />

}

Monday, April 4, 2016

Delete selected item from DropdownList / Select List Using JQuery

In this article i will show you how to delete selected item from DropdownList/Select List Using JQuery. We all know that select/DropdownList contain option tag for value. So, the main logic behind the question is first to get the select list by using their id property then use option tag with selected attribute after that remove.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default10.aspx.cs" Inherits="Default10" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>

        $(function () {
            $("#btdel").bind("click", function () {
                $("#fruitlist option:selected").remove();
            });
                    });


    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <select id="fruitlist">

        <option value="1">Mango</option>
        <option value="2">Apple</option>
        <option value="3">Orange</option>
        <option value="4">Grapes</option>



    </select>
        <input type="button" id="btdel" value="Delete" />
    </div>
    </form>
</body>
</html>

GridView Row Delete using Delete Command Name Example in ASP.NET C#

In this video i will explain you how to delete row from GridView as well as Database in ASP.NET C#. The main logic behind the code is CommandName, i.e predefined in asp.net library. If you want to update row then you have a Update command Name similarly if you want to delete row from GridView then you have Delete command Name and their respective event. Keep watching and learn better.


© Copyright 2013 Computer Programming | All Right Reserved