A step by step guide to use radio buttons as a template column in
VS2005 within a gridview. Selecting a radio button will result in
the row being selected.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public partial class _Default : System.Web.UI.Page
{
private string connectionstring =
"server=YOURSERVER;database=DB;uid=user;password=password;";
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
//Bind Master Details
BindData();
}
}
private void BindData()
{
//====Query For Master Rows======================
string QueryString = "SELECT distinct top 10 OrderID, ShipName as Name, " +
"ShipCity as City, ShipRegion as Region, ShipPostalCode as Postal " +
"FROM Orders order by ShipName";
//================================================
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
try
{
conn.ConnectionString = connectionstring;
if (conn.State == System.Data.ConnectionState.Closed)
{
//OPEN CONNECTION
conn.Open();
}
//FILL DATASET
System.Data.SqlClient.SqlDataAdapter adapter =
new System.Data.SqlClient.SqlDataAdapter(QueryString, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
catch (Exception ex1)
{
Response.Write("An error has occurred: ");
Response.Write(ex1.Message.ToString());
Response.End();
}
finally
{
if (conn.State == System.Data.ConnectionState.Open)
{
//CLOSE CONNECTION
conn.Close();
}
}
}
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
LabelSelected.Text = "";
//Clear Selection
GridView1.SelectedIndex = -1;
//Get the RadioButton Which Was Selected
RadioButton SelectedRadioButton = (RadioButton)sender;
//Since this is a template column,
//we can get the specific row, by using
//the Naming Container.
GridViewRow SelectedGridRow = (GridViewRow)SelectedRadioButton.NamingContainer;
//Clear All Radio Button Choices From Prior
foreach (GridViewRow GridRow in GridView1.Rows)
{
if (GridRow != SelectedGridRow)
{
RadioButton RowRadioButton =
(RadioButton)GridRow.FindControl("RadioButton1");
RowRadioButton.Checked = false;
}
}
if (SelectedRadioButton.Checked == true)
{
//Set the row as selected
GridView1.SelectedIndex = SelectedGridRow.RowIndex;
//Print out details of selected row data
string MessageOutput = "Items Selected are: ";
for (int i = 1; i < SelectedGridRow.Cells.Count; i++)
{
MessageOutput += GridView1.HeaderRow.Cells[i].Text + ": " +
SelectedGridRow.Cells[i].Text + "
";
}
LabelSelected.Text = MessageOutput;
}
}
}
No comments:
Post a Comment