Select single RadioButton in GridView when RadioButton’s GroupName is not working in asp.net using JavaScript


Here we will learn how to avoid Radiobutton or RadioButtonList allows multiple selections in GridView without using any RadioButton’s Group in asp.net C#
First Create Table as follows

tbl_Employee

Add the data into the table

Data

JavaScript Code:

<script language=”javascript” type=”text/javascript”>
function SetUniqueRadioButton(index) {
for (i = 0; i < IsManager.length; i++) {
var rb_Visitor = document.getElementById(IsManager[i]);
if (i == index) {
rb_Visitor.checked = true;
}
else {
rb_Visitor.checked = false;
}
}
}
</script>

Form Content:

<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
OnRowDataBound=”GridView1_RowDataBound” onprerender=”GridView1_PreRender”>
<Columns>
<asp:BoundField DataField=”EmpId” HeaderText=”Emp Id” />
<asp:BoundField DataField=”EmpName” HeaderText=”Emp Name” />
<asp:TemplateField HeaderText=”Is Manager”>
<ItemTemplate>
<asp:RadioButton ID=”rb_IsManager” GroupName=”ss” runat=”server” Text=’<%#Eval(“IsManager”) %> />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”DOJ” HeaderText=”Date of Join”
DataFormatString=”{0:d}” />
</Columns>
</asp:GridView>
</div>
</form>

ConnectionString in Web.Config file:

<connectionStrings>
        <addname=ConnectionStringconnectionString=Data Source=YourServerName;Initial Catalog=DemoDB;Persist Security Info=True;User ID=sa;Password=yourPassword/>
    </connectionStrings>

NameSpaces To Use:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

Filling GridView:

protected void Page_Load(object sender, EventArgs e)
{
GetData();
}
string connectionstring = ConfigurationManager.ConnectionStrings[“ConnectionString”].ToString();
public void GetData()
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(“select EmpId,EmpName,IsManager,DOJ from tbl_employee”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

Binding OnClick Javascript Method with RowIndex to RadioButton in GridView RowDataBound Event:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow row = (GridViewRow)e.Row;
RadioButton rb_IsManager = (RadioButton)row.FindControl(“rb_IsManager”);
rb_IsManager.Attributes.Add(“onclick”, “SetUniqueRadioButton(“ + row .DataItemIndex + “)”);
if (Convert.ToBoolean(rb_IsManager.Text))
{
rb_IsManager.Text = “”;
rb_IsManager.Checked = true;
}
else
{
rb_IsManager.Text = “”;
rb_IsManager.Checked = false;
}
}
}

Collecting all RadioButtons ClientIds in GridView PreRender Event:

protected void GridView1_PreRender(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
foreach (GridViewRow grdrow in GridView1.Rows)
{
RadioButton rb_IsManager = (RadioButton)grdrow.FindControl(“rb_IsManager”);
cs.RegisterArrayDeclaration(“IsManager”, String.Concat(“‘”, rb_IsManager.ClientID, “‘”));
}
}

Complete Code:

(.aspx)

<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Radiobuttongroup in grid.aspx.cs”
Inherits=”Radiobuttongroup_in_grid” %><!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>

<script language=”javascript” type=”text/javascript”>
function SetUniqueRadioButton(index) {
for (i = 0; i < IsManager.length; i++) {
var rb_Visitor = document.getElementById(IsManager[i]);
if (i == index) {
rb_Visitor.checked = true;
}
else {
rb_Visitor.checked = false;
}
}
}
</script>

</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False”
OnRowDataBound=”GridView1_RowDataBound” onprerender=”GridView1_PreRender”>
<Columns>
<asp:BoundField DataField=”EmpId” HeaderText=”Emp Id” />
<asp:BoundField DataField=”EmpName” HeaderText=”Emp Name” />
<asp:TemplateField HeaderText=”Is Manager”>
<ItemTemplate>
<asp:RadioButton ID=”rb_IsManager” GroupName=”ss” runat=”server” Text=’<%#Eval(“IsManager”) %> />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”DOJ” HeaderText=”Date of Join”
DataFormatString=”{0:d}” />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

(.aspx.cs)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;public partial class Radiobuttongroup_in_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetData();
}
string connectionstring = ConfigurationManager.ConnectionStrings[“ConnectionString”].ToString();
public void GetData()
{
SqlConnection con = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(“select EmpId,EmpName,IsManager,DOJ from tbl_employee”, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow row = (GridViewRow)e.Row;
RadioButton rb_IsManager = (RadioButton)row.FindControl(“rb_IsManager”);
rb_IsManager.Attributes.Add(“onclick”, “SetUniqueRadioButton(“ + row .DataItemIndex + “)”);
if (Convert.ToBoolean(rb_IsManager.Text))
{
rb_IsManager.Text = “”;
rb_IsManager.Checked = true;
}
else
{
rb_IsManager.Text = “”;
rb_IsManager.Checked = false;
}
}
}
protected void GridView1_PreRender(object sender, EventArgs e)
{
ClientScriptManager cs = Page.ClientScript;
foreach (GridViewRow grdrow in GridView1.Rows)
{
RadioButton rb_IsManager = (RadioButton)grdrow.FindControl(“rb_IsManager”);
cs.RegisterArrayDeclaration(“IsManager”, String.Concat(“‘”, rb_IsManager.ClientID, “‘”));
}
}
}

OutPutScreen:

Select single RadioButton in GridView when RadioButton's GroupName is not working in asp.net using JavaScript

=======================================================>0<=====================================================================

Happy Coding

=======================================================>0<=====================================================================

Advertisements

Dynamic Gridview binding in asp.net c# by getting data from StoredProcedure


Table Design:

TableDesign Data In Table:

DatainTable

Stored Procedure:

create procedure sp_GetCustomers
as
begin
select * from dbo.customer
end

Code in Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code in Default.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=SourceName;Initial Catalog=DbName;User ID=sa;Password=YourPassword");
        SqlCommand cmd = new SqlCommand("sp_GetCustomers", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

OutPut:

Dynamic Gridview binding in asp.net c# by getting data from StoredProcedure

How to append text to a Eval databound field in gridview in asp.net?


We will use Databinders to bind data to controls.

Sometimes we need to append some text before data or after data… ex: we can append Download text before to DocumentName

we can do this as follows

Append Text before Eval Data

  1. <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/DwonloadFile.png" ToolTip='<%#"Download" +" "+ Eval("DocumentName").ToString() %>'/>

Append Text before and after Eval Data

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/DwonloadFile.png" ToolTip='<%#"Download" +" "+ Eval("DocumentName").ToString()+" "+ "TextFile"%>'/>

Concatenating Two Eval binders

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/DwonloadFile.png" ToolTip='<%#"Download" +" "+ Eval("DocumentName").ToString()+" as "+ Eval("Format").ToString()%>'/>

By using string.Format() Method in Eval

Append Text before Eval Data

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/DwonloadFile.png" ToolTip='<%#string.Format("Download {0}",Eval("DocumentName")) %>'/>

Append Text before and after Eval Data

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/DwonloadFile.png" ToolTip='<%#string.Format("Download {0} as TextFile",Eval("DocumentName")) %>'/>

Concatenating Two Eval binders

<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/Images/DwonloadFile.png" ToolTip='<%#string.Format("Download {0} as {1}",Eval("DocumentName"),Eval("Format")) %>'/>

Thanks…

Venki

Hi if this is not solving ur problem please leave ur requirement as a comment below this post…

How to bind Dropdownlist in gridview using EntityFramework(EDM)


First Take new web site and add .edmx file

if you don’t know how to add .edmx file Clickhere

then add new webform and place a gridview as follows

then write this code in codebehind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = from n in en.UserDetails select n;
            GridView1.DataBind();
        }
    }
    MySampleDBModel.MySampleDBEntities en = new MySampleDBModel.MySampleDBEntities();
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            var x = from n in en.UserDetails
                    select new { n.UserId, n.UserName };
            DropDownList ddl = (DropDownList)e.Row.FindControl("DropDownList1");
            ddl.DataTextField = "UserName";
            ddl.DataValueField = "UserId";
            ddl.DataSource = x;
            ddl.DataBind();
        }
    }
}

Output:

how to change row background color of gridview


Create DataBase as follows:

Design .aspx as follows:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title>Gridview onmouseover and onmouseout</title>
<script type="text/javascript">
var oldgridcolor;
function SetMouseOver(element) {
oldgridcolor = element.style.backgroundColor;
element.style.backgroundColor = '#FF9966';
element.style.cursor = 'pointer';
element.style.textDecoration = 'underline';
}
function SetMouseOut(element) {
element.style.backgroundColor = oldgridcolor;
element.style.textDecoration = 'none';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvrecords" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White"
onrowdatabound="gvrecords_RowDataBound" BackColor="#DEBA84" BorderColor="#DEBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">

<Columns>
<asp:BoundField DataField="UserName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />

<HeaderStyle BackColor="#A55129" ForeColor="White" Font-Bold="True"></HeaderStyle>
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</div>
</form>
</body>
</html>

Then write Following Code in CodeBehind:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "javascript:SetMouseOver(this)";
            e.Row.Attributes["onmouseout"] = "javascript:SetMouseOut(this)";
        }
    }
    protected void BindGridview()
    {
        SqlConnection con = new SqlConnection("Data Source=server2;user id=sa;password=123;Initial Catalog=MySampleDB");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from UserDetails", con);
        cmd.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvrecords.DataSource = ds;
        gvrecords.DataBind();
    }

OutPut:

DownLoadSampleCode

how to call javascript function from gridview onmouseover,onmouseout


sometimes we need to call javascript function from gridview

this post will help to do that

First create database table as follows

Then design .aspx page as follows:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title>Gridview onmouseover and onmouseout</title>
<script type="text/javascript">
    var oldgridcolor;
    function SetMouseOver(element) {
        alert("Welcome to onmouseover event.!");
    }
    function SetMouseOut(element) {
//        alert("welcome to onmouseout event");
    }
</script>
</head>
<body style="font-weight: 700">
<form id="form1" runat="server">
<div>
  <asp:GridView runat="server" ID="gvrecords"AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White"
onrowdatabound="gvrecords_RowDataBound" BackColor="#DEBA84" BorderColor="#DEBA84"
        BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2">
<Columns>
<asp:BoundField DataField="UserName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" ForeColor="White" Font-Bold="True"></HeaderStyle>
    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FFF1D4" />
    <SortedAscendingHeaderStyle BackColor="#B95C30" />
    <SortedDescendingCellStyle BackColor="#F1E5CE" />
    <SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</div>
</form>
</body>
</html>

Then Write Following Code in Code Behind:

 
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //here we are setting onmouseover events
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "javascript:SetMouseOver(this)";
            e.Row.Attributes["onmouseout"] = "javascript:SetMouseOut(this)";
        }
    }
    protected void BindGridview()
    {
        SqlConnection con = new SqlConnection("Data Source=server2;user id=sa;password=123;Initial Catalog=MySampleDB");
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from UserDetails", con);
        cmd.ExecuteNonQuery();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvrecords.DataSource = ds;
        gvrecords.DataBind();
    }

How to retrieve data from database using EntityFrameWork


Create database tables as follows:

First add ADO.NET entity data modal to our project

Display data using grid view:

Form Design:

Add new form and place a GridView in form.

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</div>
</form>
</body>
</html>

Code Behind:

Write following code in pageload event:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        GetData();
    }
}
public void GetData()
{
    //first create object to the EDMEntities as follows…
    sampledatabaseModel.sampledatabaseEntities obj = new sampledatabaseModel.sampledatabaseEntities();
    //retrive data using edm…
    var x = (from n in obj.emps select n);
    //bind data to gridview
    GridView1.DataSource = x;
    GridView1.DataBind();
}

======================================================

How to get data from database based on some parameter using EntityFrameWork

Form Design:

1.Keep one gridview  to display data

2.One textbox to enter parameter

3.One button to send value

4.One literal to display error message

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
<br />
Enter EmpNo:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>

Code behind:

In form load write above code only

Then write following code in button click event

if (TextBox1.Text.Trim() != string.Empty)
{
int i = int.Parse(TextBox1.Text);
var x = (from n in obj.emps
where n.eno == i
select n);
if (x != null)
{
GridView1.DataSource = x;
GridView1.DataBind();
}
else
{
Literal1.Text = "Enter Proper Empid from above details";
GetData();
}
}
else
Literal1.Text = "textbox should not be empty";