Monday, February 23, 2009

How to read data from sql server stored procedure using asp.net




Please visit my new Web Site https://coderstechzone.com



Reading Sql Server data is a most common task in our lives. In this case i am considering the best ways To read Sql server stored procedure data using asp.net. I have no intension to write more on SP/asp.net code. I just want to show some easy steps which may reduce our most valuable time To retrieve data from Sql Server.

Click Here to read How to create Dynamic SQL in SP.

To start, first create a simple stored procedure. SP code looks like:

CREATE PROCEDURE SP1
AS
BEGIN
SELECT Region,GP FROM RMS
END

Now we can retrieve data from it using asp.net in the following way:
string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
SqlConnection Conn = new SqlConnection(sConstr);

using (Conn)
{
SqlCommand command = new SqlCommand("SP1", Conn);
command.CommandType = CommandType.StoredProcedure;
Conn.Open();
SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
Response.Write(reader.GetString(0) + "\t" + reader.GetSqlInt64(1).ToString());

reader.Close();
}

Now trying a little bit complex stored procedure. In this procedure we will try to retrieve record set by applying few filtering. For an example the SP like:
ALTER PROCEDURE SP2(@Param1 bigint=0,@Param2 bigint=0)
AS
BEGIN
SELECT Region,GP,BL FROM RMS WHERE GP>@Param1 AND BL>@Param2 ORDER BY 1
END

Here @Param1 bigint=0 means default value. If you do not provide any value for @Param1 then sp will consider 0.

To run this SP from Query Analyzer follow the below sql:
EXEC SP2 @param2=10

We know how we can read record set from database in the previous example but we do not know how we can send input parameters from asp.net to sql server. The following code shows the way:
string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
SqlConnection Conn = new SqlConnection(sConstr);

using (Conn)
{
SqlCommand command = new SqlCommand("SP2", Conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@Param1", SqlDbType.BigInt));
command.Parameters["@Param1"].Value = 8;
command.Parameters.Add(new SqlParameter("@Param2", SqlDbType.BigInt));
command.Parameters["@Param2"].Value = 10;
Conn.Open();
SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
Response.Write(reader.GetString(0) + "\t" + reader.GetSqlInt64(1).ToString());

reader.Close();
}

Now we can read records from SP with input parameters. But sql server provide us another option for parameter which is termed as OUTPUT parameter. Means we can send input parameter for filtering data within SP as well as we can send an output parameter to cath a value like "Call by ref" in asp.net or other languages. Sample SP to run the example is:

Don't forget to specify the size for VARCHAR. IF not specified then SP treats the size is 1.
ALTER PROCEDURE SP3(@Param1 bigint,@Param2 bigint,@oParam3 VARCHAR(500) OUTPUT,@oParam4 bigint OUTPUT)
AS
BEGIN
SELECT Region,GP,BL FROM RMS WHERE GP>@Param1 AND BL>@Param2 ORDER BY 1
SELECT @oParam3=Region,@oParam4=COUNT(*) FROM RMS GROUP BY Region ORDER BY 2 DESC
RETURN
END

Sample code to run SP within query analyzer:
declare @oParam3 varchar(500)
declare @oParam4 bigint
EXEC SP3 10,10,@oParam3 OUTPUT,@oParam4 OUTPUT
print @oParam3

Now the below code will show how we can read recordes using asp.net
string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
SqlConnection Conn = new SqlConnection(sConstr);

using (Conn)
{
SqlCommand command = new SqlCommand("SP3", Conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@Param1", SqlDbType.BigInt));
command.Parameters["@Param1"].Value = 8;
command.Parameters.Add(new SqlParameter("@Param2", SqlDbType.BigInt));
command.Parameters["@Param2"].Value = 10;

// MOST COMMON MISTAKE TO AVOID THE SIZE ARGUMENT
SqlParameter GreaterRegion = new SqlParameter("@oParam3", SqlDbType.VarChar, 500);
GreaterRegion.Direction = ParameterDirection.Output;
command.Parameters.Add(GreaterRegion);
SqlParameter Counter = new SqlParameter("@oParam4", SqlDbType.BigInt);
Counter.Direction = ParameterDirection.Output;
command.Parameters.Add(Counter);

Conn.Open();
SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
Response.Write(reader.GetString(0) + "\t" + reader.GetSqlInt64(1).ToString());

reader.Close();
// TO READ OUTPUT PARAMETER VALUE KEEP IN MIND THAT YOU MUST USE AFTER READER CLOSED.
Response.Write("Large Region is: " + GreaterRegion.Value.ToString()+" Contains:"+Counter.Value.ToString());
}

So now we have completed reading SP with input & output parameter. Now we try to improve our coding technique. Lets we have a stored procedure which has 100+ input/output parameters. To make life easier we can follow the below way:
private void ExecSP(string procName, string[] paramName, Object[] paramValue)
{
string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
SqlConnection Conn = new SqlConnection(sConstr);

SqlCommand command = new SqlCommand(procName, Conn);
command.CommandType = CommandType.StoredProcedure;

for (int i = 0; i < paramName.Length; i++)
command.Parameters.AddWithValue(paramName[i], paramValue[i]);

Conn.Open();
SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
Response.Write(reader.GetString(0) + "\t" + reader.GetSqlInt64(1).ToString() + "<BR/>");

reader.Close();
}

And run it from asp.net like:
ExecSP("SP2",new string[] { "@Param1","@Param2" }, new object[] { 8,10 });

For better reusability you can modify the above ExecSP by returnning a Ienumerable collection/datatable in your application data layer.

NOTE:
**Always wrap disposable objects like connections, commands and readers in using statements.
**This provides several advantages: cleaner code, exception safe and less code.
**To read large volume of data use sqldatareader instead of data dataadapter because its read only.
**Connection will be more efficient in using SQLDataAdapter class.

Saturday, February 21, 2009

Selecting all check boxes in a gridview control




Please visit my new Web Site https://coderstechzone.com



By using client script selecting all check boxes in a gridview control is a most common task. Here i am trying to show an example for begginers how we can provide this functionality into our pages to enhance user experience. Here i am using a tempalte column to add both header checkbox & rows checkbox in the gridview. When user click on the header checkbox then a javascript method will be invoked To select/deselect all checkboxes inside the gridview rows depends on header checkbox checked property. Like:


So to do that at first i need to add a gridview control in my aspx page. Code like:
<b>List of suppliers:</b>

<asp:GridView runat="server" ID="gvEdit" DataKeyNames="ID" AutoGenerateColumns="false" >
<Columns>

<asp:TemplateField HeaderText="Select">
<ItemTemplate><asp:CheckBox runat="server" ID="chk"/></ItemTemplate>
<HeaderTemplate>
<input id="chkAll" onclick="javascript:GridSelectAllColumn(this, 'chk');" runat="server" type="checkbox" value="" />
</HeaderTemplate>
</asp:TemplateField>

<asp:BoundField DataField="Code" HeaderText="Code" ></asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="Name" ></asp:BoundField>
<asp:BoundField DataField="Address" HeaderText="Address"></asp:BoundField>
<asp:BoundField DataField="Contact" HeaderText="Contact no"></asp:BoundField>

</Columns>
</asp:GridView>


Now gridview control added in our page. So now we can populate our gridview from serverside code. I hope its not necessary to provide server side code in this post.

Now to acheive our goal we need to do just adding a javascript function. Add the following javascript function to select all check boxes within a GridView.

function GridSelectAllColumn(spanChk, chkName)
{

var oItem = spanChk.children;
var theBox= (spanChk.type=="checkbox") ? spanChk : spanChk.children.item[0]; xState=theBox.checked;
elm=theBox.form.elements;

for(i=0;i -1)
{
if(elm[i].checked != xState)
elm[i].click();
}//end for

}//end func

Hope now it will work perfectly. For further study you can try with jquery :)

Friday, February 20, 2009

Automaticaly refresh parent window after popup is closed




Please visit my new Web Site https://coderstechzone.com



For data driven web application most of the times we did this job. There are lot of way to handle this issue. Here i am trying to show you few process that how we can handle it. To describe this problem here i am using datatable instead of database since anyone can replace my code easily by his own data reader block. Let we have a requirement that a page contains list of suppliers. Below the supplier list client wants to add a link to add more suppliers like:

If user click on add more supplier link then the link open a popup to enter supplier details. After entering the supplier details when user click on the save button then system automatically save the data & close the popup as well as reflect the currently added row to the opener like:


So now we can start step by step. At first add a page named parentrefresh.aspx. Then add a gridview to display the existing suppliers. After the gridview we need to add a link button/html button to popup the window. So parentrefresh.aspx looks like:

<b>List of suppliers:</b>

<asp:GridView runat="server" ID="gvEdit" DataKeyNames="ID" AutoGenerateColumns="false" ">
<Columns>
<asp:BoundField DataField="Code" HeaderText="Code"></asp:BoundField>
<asp:BoundField DataField="Name" HeaderText="Name"></asp:BoundField>
<asp:BoundField DataField="Address" HeaderText="Address"></asp:BoundField>
<asp:BoundField DataField="Contact" HeaderText="Contact no"></asp:BoundField>
</Columns>
</asp:GridView>

<asp:LinkButton runat="server" OnClientClick="window.open('childrefresh.aspx');return false;"
ID="lnkNew">Add more supplier
</asp:LinkButton>

To read existing supplier data from database(here i use datatable for simplicity) we need to write few server side code in page load event. Codes:
if (!IsPostBack)
{
DataTable dtSupplier;
if (Session["dtSupplier"]==null)
{
//If not populated previously then we need to populate data. Otherwise we read from session.
dtSupplier = new DataTable("Supplier");
dtSupplier.Columns.Add(new DataColumn("ID", System.Type.GetType("System.UInt64")));
dtSupplier.Columns.Add(new DataColumn("Code"));
dtSupplier.Columns.Add(new DataColumn("Name"));
dtSupplier.Columns.Add(new DataColumn("Address"));
dtSupplier.Columns.Add(new DataColumn("Contact"));
dtSupplier.Rows.Add(1, "st0001", "S.R. Steel", "Uttara, Dhaka", "01711xxxxxx");
dtSupplier.Rows.Add(2, "ir0039", "Shadesh builders", "Rampura, Dhaka", "01711yyyyyy");
dtSupplier.Rows.Add(3, "cr0042", "Orchard confec.", "Shahabag, Dhaka", "01711zzzzzz");
dtSupplier.Rows.Add(4, "er0078", "Windblow", "Mirpur, Dhaka", "01711qqqqqq");
dtSupplier.Rows.Add(5, "bd0301", "Rahimkarim", "Badda, Dhaka", "01711oooooo");
Session["dtSupplier"] = dtSupplier;
}
else
dtSupplier = (DataTable)Session["dtSupplier"];
gvEdit.DataSource = dtSupplier;
gvEdit.DataBind();
}

Now we need to add another page named childrefresh.aspx which will be our popup window. If you look at the first page link button click event then you found this page url as a popup. Find the child page html contents from below:

The onunload event basically refresh the parent page. Here you can refresh parent page by location or reload by using onunload="window.opener.location.reload();"
Or you can call a javascript function within onunload handler. Initially start with below code. After than practice above ways.
<body onunload="window.opener.location=window.opener.location;">
<form id="form1" runat="server">
<div>
<table border="0">
<tr><td>Code:</td><td>
<asp:TextBox runat="server" ID="txtCode"></asp:TextBox></td></tr>
<tr><td>Name:</td><td>
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>
</td></tr>
<tr><td>Address:</td><td>
<asp:TextBox runat="server" ID="txtAddress"></asp:TextBox></td></tr><tr><td>Contact no:</td><td>
<asp:TextBox runat="server" ID="txtContact"></asp:TextBox></td>
</tr>
</table>
</div>
<asp:LinkButton runat="server" ID="lnkSave" OnClick="lnkSave_Click">Save & close</asp:LinkButton>

Now we need to write few code under save button to add supplier data in session datatable so parent page can read the currently saved data:
protected void Page_Load(object sender, EventArgs e)
{
//session time may be expired/user may open the popup directly other wise page gives error.
if (Session["dtSupplier"] == null)
return;
}

protected void lnkSave_Click(object sender, EventArgs e)
{
DataTable dtSupplier = (DataTable)Session["dtSupplier"];
dtSupplier.Rows.Add(1, txtCode.Text, txtName.Text, txtAddress.Text, txtContact.Text);
Session["dtSupplier"] = dtSupplier;
//below line register the close block in the page which will run imediately & close the popup.
ClientScript.RegisterStartupScript(GetType(),"tst", "<script>window.close();</script>");
}

Now our example is ready. Just run...........

Few considerations:
If you open the popup by window.open() then you also can use:

window.opener.location.reload(true); // Make a new request to the server.
window.opener.location.reload(false); // Attempt from the cache.

If you use window.showModalDialog and self as the second parameter then use:

window.dialogArguments.location.reload(true); // Put before close
OR
window.dialogArguments.location = window.dialogArguments.location;

Using this way you can change the query parameter of parent window/provide a completely a new url. Interesting.........

One another thing sometime you would like To know the parent address due to security issue or To handle multiple opener for a popup, that time you can use window.opener.location.href To validate the parent window.

Thursday, February 19, 2009

Building asp.net(c#) database driven event calendar




Please visit my new Web Site https://coderstechzone.com



Tracking events based on date is one of the most common requirements in our daily lives. Event calendar is one of the most popular solution where user can easily track his/her or agents or subordinates daily most important activies. Most of the free components probably can't implement your demand. In asp.net you can use calendar control to fullfill custom demands. But i am trying to develop a calendar without using calendar control. To do this i choose DataList because here i can define column no & repeat direction which make me interested. I want to produce my output like below:

At first add a datalist control in your page. Use a HeaderTemplate column to generate custom header where you will place year combo control & month navigation link. Add ItemTemplate to create day wise block within the calendar. The code looks like:

<asp:DataList ID="dlCalendar" runat="server" RepeatColumns="7" Width="600px" BorderStyle="None" RepeatDirection="Horizontal" OnItemDataBound="dlCalendar_ItemDataBound">

<HeaderTemplate>
<table width="100%" border="0" cellpadding="0" cellspacing="0" style="background-color:#00BFFF;height:20px"><tr><td width="33%"><asp:DropDownList runat="server" ID="cboPrev" AutoPostBack="true" Width="70px" OnSelectedIndexChanged="RfreshData"></asp:DropDownList>
<asp:Label runat="server" ID="lblLeft" ></asp:Label>
</td><td width="33%" align="Center"><asp:Label runat="server" ID="lblMiddle" >
</asp:Label></td><td width="33%" align="right">
<asp:Label runat="server" ID="lblRight" ></asp:Label>
<asp:DropDownList runat="server" ID="cboNext" Width="70px" OnSelectedIndexChanged="RfreshData"></asp:DropDownList></td></tr>
</table>
</HeaderTemplate>

<ItemTemplate><table border="0" style="background-color:Silver" width="130px" style="height:100px" cellpadding="0" cellspacing="0" ><tr><td align="left" valign="top"">
<asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Data") %>' Width="100%"></asp:Label>
</td></tr></table>
</ItemTemplate>

</asp:DataList>

For simplicity here i use datatable. But you can easily replace the datatable by populating data from database. So at first i need to populate event data then combind this data with date block of the calendar. To do that i write the below code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DateTime dDate;
if (Request["SpecificMonth"] != null)
dDate = Convert.ToDateTime(Request["SpecificMonth"]);
else
dDate = DateTime.Now;

// Here you need to made the datastructure in such a way that you can bind the data in your datalist easily.
// So give concentration on database query to produce data like below:
// You can display each event, description if you can make the data row appropriately.

DataTable dtEvents = new DataTable("DailyEvents");
dtEvents.Columns.Add(new DataColumn("EventDate", System.Type.GetType("System.DateTime")));
dtEvents.Columns.Add(new DataColumn("EventType"));
dtEvents.Columns.Add(new DataColumn("EventDescription"));
dtEvents.Columns.Add(new DataColumn("Done"));
dtEvents.Columns.Add(new DataColumn("Note"));

dtEvents.Rows.Add(DateTime.Now,"Meeting", "BSSOM", "Attended?", "Agenda: 1)Indexing problem in ABC server. 2) Fix time to go Live. 3) Who will be responsible to maintain it?");

dtEvents.Rows.Add(DateTime.Now.AddDays(5),"Travel", "Coxsbazar", "Visited?", "Agenda: 1) Go to barmiz market 2) Buy few cloths for my wife 3) Eat rupchanda fish");

dtEvents.Rows.Add(DateTime.Now,"Assignment", "Audit", "R&D Done?", "");
dtEvents.Rows.Add(DateTime.Now, "Rport", "Fin. report", "Ready?", "");
dtEvents.Rows.Add(DateTime.Now.AddDays(5), "Birthday", "Shumon", "Send gift?", "");

DataTable datatable = new DataTable();
datatable.Columns.Add("Day"); //day contains day of the month
datatable.Columns.Add("Data"); //run time produce html & just place on it.
DataRow oRow;

for (int i = 1; i <= DateTime.DaysInMonth(dDate.Year, dDate.Month); i++)
{

DateTime dCalendarDay = new DateTime(dDate.Year, dDate.Month, i);
oRow = datatable.NewRow(); // here i am preparing data for a specific day.
// bworkingday method return: does the day is off or not.
// You can apply you business logic in this function to reurn data.
// by getEvents method i collect this day events from my all data.
// you can add control & event handler in runtime for more interactive calendar.

if (!bWorkingDay(dCalendarDay))
oRow["Data"] = i.ToString() + " " + dCalendarDay.ToString("ddd") + " " + getEvents(dCalendarDay, dtEvents);
else
oRow["Data"] = i.ToString() + " " + dCalendarDay.ToString("ddd") + " " + getEvents(dCalendarDay, dtEvents);
datatable.Rows.Add(oRow);

}

dlCalendar.DataSource = datatable;
dlCalendar.DataBind();

// here just i am making current date block.
if (dDate.Year == DateTime.Now.Year && dDate.Month == DateTime.Now.Month)
{
foreach (DataListItem oItem in dlCalendar.Items)
{
if (oItem.ItemIndex == DateTime.Now.Day - 1)
{
oItem.BorderStyle = BorderStyle.Solid;
oItem.BorderColor = System.Drawing.Color.DeepSkyBlue; oItem.BorderWidth = 2;
}// if closed
}// for closed
}// if closed

}// !IsPostBack
}// Page_Load

In the above code block i use few fuctions like:
public string getEvents(DateTime dDate, DataTable dTable)
{
string str = "";
foreach (DataRow oItem in dTable.Rows)
{
if (Convert.ToDateTime(oItem["EventDate"].ToString()).ToString("dd MMM, yyyy") == dDate.ToString("dd MMM, yyyy"))
{
str = str + " " + oItem["EventType"] + ":" + oItem["EventDescription"] + " ";
}
}
return str;
}

public bool bWorkingDay(DateTime bDate)
{
// here i am assuming the sunday as holiday but you can make it more efficiently
// by using a databse if you want to generate country based calendar.
// In different country they have different holidays schedule.
if (bDate.ToString("ddd") == "Sun")
return true;
return false;
}

Now add the dlCalendar_ItemDataBound handler to populate header row of the datalist. Method code looks like:
protected void dlCalendar_ItemDataBound(object sender, DataListItemEventArgs e)
{
// Just populationg my header section
DateTime dDate;
if (Request["SpecificMonth"] != null)
dDate = Convert.ToDateTime(Request["SpecificMonth"]);
else
dDate = DateTime.Now;
if (e.Item.ItemType == ListItemType.Header)
{
DropDownList oPrev = (DropDownList)e.Item.FindControl("cboPrev");
DropDownList oNext = (DropDownList)e.Item.FindControl("cboNext");
DataTable dtYear = new DataTable();
dtYear.Columns.Add("year4");
dtYear.Columns.Add("sValue");
//here i am assuming that when user click on 2009 he wants to see january 2009 calendar.
//it will be more interective if you generate the current month(shown in the page) calendar.
dtYear.Rows.Add("2009", "01 Jan, 2009");
dtYear.Rows.Add("2010", "01 Jan, 2010");
oPrev.DataTextField = "year4";
oPrev.DataValueField = "sValue";
oPrev.DataSource = dtYear;
oPrev.DataBind();
oNext.DataTextField = "year4";
oNext.DataValueField = "sValue";
oNext.DataSource = dtYear;
oNext.DataBind();

((Label)e.Item.FindControl("lblLeft")).Text = " <a style="'color:White'" href="eventcalendar.aspx?SpecificMonth="">" + dDate.AddMonths(-1).ToString("MMMM yyyy") + "</a>";

((Label)e.Item.FindControl("lblMiddle")).Text = dDate.ToString("MMMM yyyy");

((Label)e.Item.FindControl("lblRight")).Text = "<a style="color:White" href="eventcalendar.aspx?SpecificMonth="">" + dDate.AddMonths(+1).ToString("MMMM yyyy") + "</a> ";
}
}

Now almost completed our calendar except corner year combo. To raise the selectedeventchange event must set AutoPostBack property to true. When user select a year then we just redirect him by a querystring & then we generate the calendar based on user selection by reading the query string. Code like:
protected void RfreshData(object sender, System.EventArgs e)
{
//redirect by date thats why page can render the calendar according to user selection
Response.Redirect("eventcalendar.aspx?SpecificMonth=" + ((DropDownList)sender).SelectedValue);
}

Conclusion:
This approach requires more coding. You can reduce effort by using builtin calendar control. So lets try.

Problem to group radio button across gridview rows




Please visit my new Web Site https://coderstechzone.com



Why?
In general no one can easily group or make a single selection from radio button list inside gridview rows horizontally or grouping radio button within a Gridview row. There are a lot of way to make a single or unique selection from list. Here i want to share how i can address this problem in the most easiest way. Googling the problem most of the cases i found wrong javascript. Thats why i have decided to share with you my work around. Also i have showed another way of grouping vertically Radio buttons in a Gridview. To read Vertical grouping CLICK HERE. Here in this post i will try to group the radio buttons in Horizontal way using core javascript. It will also work in master page. Let say i have a requirement like below:



Now try to resolve this issue:
At first i need to add a gridview in my page ok? So add a gridview in the page. For bind columns i need to add two bind columns & for single choice i need to add 3 template columns. Within template columns i need to add radio button. My grid view backend code looks like:
<asp:GridView runat="server" ID="gvEdit" DataKeyNames="ID" AutoGenerateColumns="false"> 
<columns>
    <asp:boundfield datafield="Code" headertext="Supplier code" horizontalalign="Left" backcolor="graytext">
    <asp:boundfield datafield="Name" headertext="Supplier name" horizontalalign="Left" backcolor="graytext">

    <asp:TemplateField headertext="High">
        <ItemStyle HorizontalAlign="Center" />
        <ItemTemplate>
            <asp:RadioButton runat="server" id="chkBar" onclick="javascript:GridSelectAllColumn(this, 'chkHigh');"/>
        </itemtemplate>
    </asp:TemplateField>

    <asp:templatefield headertext="Medium">
    <ItemStyle HorizontalAlign="Center" /> 
        <itemtemplate>
            <asp:radiobutton runat="server" id="chkLine" onclick="javascript:GridSelectAllColumn(this, 'chkMid');"/>
        </itemtemplate>
    </asp:templatefield>
    
    <asp:templatefield headertext="Low">
    <ItemStyle HorizontalAlign="Center" />
        <itemtemplate>
        <asp:radiobutton runat="server" id="chkStacked" onclick="javascript:GridSelectAllColumn(this, 'chkLow');"/>
        </itemtemplate>
    </asp:templatefield>
</columns>
</asp:GridView>
Now i think how i can provide single selection within horizontal column without post back the page to the page to the server. So i have an option javascript. Lets try to write the javascript function:
function GridSelectAllColumn(objType, chkName)
{
    var oItem = objType.children;
    var theBox=(objType.type=="radio")?objType:objType.children.item[0];
    var strPart=theBox.id.split("_");
    xState=theBox.checked;
    elm=theBox.form.elements;
    for(i=0;i<elm.length;i++)
        if(elm[i].type=="radio" && elm[i].id!=theBox.id && elm[i].id.indexOf(strPart[3])>-1)
            elm[i].checked=!xState;
}
Ok now our javascript function is ready for action. So whats next. I need to bind data from database to my gridview. For simplicity here i am using a datatable to bind the data. I wrote below code in my Page_Load method:
if (!IsPostBack)
{
DataTable dtSupplier = new DataTable("Supplier");
dtSupplier.Columns.Add(new DataColumn("ID",System.Type.GetType("System.UInt64")));
dtSupplier.Columns.Add(new DataColumn("Code"));
dtSupplier.Columns.Add(new DataColumn("Name"));
dtSupplier.Rows.Add(1, "st0001", "S.R. Steel");
dtSupplier.Rows.Add(1, "ir0039", "Shadesh builders");
dtSupplier.Rows.Add(1, "cr0042", "Orchard confec.");
dtSupplier.Rows.Add(1, "er0078", "Windblow");
dtSupplier.Rows.Add(1, "bd0301", "Rahimkarim");
gvEdit.DataSource = dtSupplier;
gvEdit.DataBind();
}

Now i run the page & i got exactly what i want "The single & unique selection or choice". If anyone closely observe my javascript method then you may find a tricks regarding radio object id. Isn't it??

Don't worry use unique radio button id, will resolve this problem :)

Tuesday, February 17, 2009

Important javascript Event List & Description




Please visit my new Web Site https://coderstechzone.com



Event?
Event means action. When user click a button means user wants to perform an action. Events like performing:

  1. Click on a button
  2. Press a key
  3. Highlight text
  4. Drag & Drop

List of available javascript Events are given below:
*To see the example scroll down
EventDescriptionApplicable for ?
onAbortWhen user cancel image loadingImage
onBlurWhen control lost its FocusButton, Checkbox, FileUpload, Layer, Password, Radio, Reset, Select, Submit, Text, TextArea, Window
onChangeCombo index change/Textbox data changeText, TextArea, Select
onClickMost useful event. Occur when user click on a buttonButton, Checkbox, Link, Radio, Submit
onDblClickWhen user double click on a LinkLink
onFocusWhen an object get focusButton, Checkbox, Radio, Reset, Select, Submit, Text, TextArea
onKeyDownWhen the key is down means pressing timeLink, TextArea
onKeyPressWhen user presses/holds a keyLink, TextArea
onKeyUpWhen user release a keyLink, TextArea
onLoadAfter completion of loading a pageWindow, Image
onMouseDownWhen mouse pressesLink, Button, Document
onMouseMoveWhen user moves the mouseLink, Button, Document
onMouseOutWhen user moves the mouse away from a objectImage, Link
onMouseOverWhen user moves the mouse over a objectImage, Link
onMouseUpWhen user release mouseDocument, Button, Link
onMoveWhen user moves the browser window or a frameDocument, Button, Link
onResetBy clicking on reset ButtonForm
onResizeWhen user resizes the browser window or a frameWindow
onSelectWhen user select textText, TextArea
onSubmitWhen user clicks the submit buttonForm
onUnloadWhen user leaves the page/close the browserWindow

Example onClick Event:
Here i am showing how one can use this event & add event handler. Example covers both asp.net server side control & HTML control. To run this example just copy the below code then run your page. Add the below function in your javascript block:
function funcOnClick()
{
// Code goes here
alert("Click event fired");
// Return false never make a post back to server.
// so one can add validation by using this concept. If return true then the page will be post back to server
return false;
}

Add the handler:
<asp:button runat="server" id="cmdOnClick" text="OnClientClick" onclientclick="return funcOnClick();">
<asp:button runat="server" id="cmdOnClick" text="OnClientClick" onclientclick="return funcOnClick();">
<asp:button runat="server" id="cmdRunTime" text="Server Control onClick">
<input type="button" name="cmdHTML" value="HTML onClick" onclick="return funcOnClick();">

For cmdRunTime here i am showing how one can bind event handler in runtime. Here i am using asp.net(c#). Add the below line under Page_Load Event:
cmdRunTime.Attributes.Add("onClick", "return funcOnClick();");

Live Demo:
----------------------------------------------------------------------------------------

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

** Click to view the practical example on onMouseOver & onMouseOut
** Click to view the practical example on onclick
** Click to view the practical example on onkeypress
** Click to view the practicle example on onunload
** Click to view the practical example on OnClientClick

Ref:
http://www.w3schools.com/jsref/jsref_events.asp
Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash