Thursday, July 22, 2010

Radio Button in Grid View


I had use radio button in grid view into my recent development.

Radio button Group problem in Grid view

I found that radio button is not create group when they are render on client side into grid rows because of the automated id and name creation of the asp.net.

Radio button checked property problem in Grid view on server side code

One more problem I found that when we iterate through grid view rows on server side code. I can find the radio button using the rows[0].findcontrol('id') method but its always give me a checked value false.

Following is solution I applied into my development to get out of this tow.

I replace Radio button server control with the HTML input control with type radio.


<asp:RadioButton ID="RadioButton1" runat="server" />

<input type="radio" runat="server" ID="radio1" class="rbclass" value='<%# Eval("columen name") %>' />


Apply server side binding to the value property of it.

I used jquery to change the name attribute of the radio button to make them grouped. (you can used you own java script code to do that)

$(document).ready(function() {
            $(".rbclass").attr("name", "groupname");
});


When I want the selected value at time of the postback I used request.form["group name"].

string radiovalue = Convert.ToString(Request.Form["groupname"]);

Tuesday, July 6, 2010

ExecuteScalar function with Generic Data Type

Here is the static function which will Generic Data Type to get the scalar value from the query passed to the ExecuteScalar function of the SqlCommand object.

You have to pass the query and the connection string as parameter to it.

public static T ExecuteScalar<T>(string query, string strConnection)
{
            SqlConnection con = new SqlConnection(strConnection);

            SqlCommand sc = new SqlCommand();
            sc.CommandText = query;
            sc.Connection = con;
            try
            {
                con.Open();
                return (T)(sc.ExecuteScalar());
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
                con.Dispose();
                sc.Dispose();
            }
        }