Dev 1
Tuesday, March 10, 2009
Retrieve gridview values using via "NamingContainer"
Simple tutorial on asp.net using c#
This tutorial tackles on retrieving row values using "NamingContainer".
Scenario: You have a gridview with a bunch of data from the DB. In your gridview you have a LinkButton named "Edit".
When you click on the "Edit" button, values from the selected row will be shown in a Textbox.
Their are a lot of approach to this kind of problem. One of which is assigning and ID to the commandArgument
of your LinkButton during Binding. You can also have the selected index.
This code will illustrate how to achieve same result by using the "NamingContainer".
protected void btnEdit_Click(object sender, EventArgs e)
{
string fname, lname, addr, phone;//Some variable declarion
LinkButton edit = ((LinkButton)sender);//Cast your sender to LinkButton to get the source of the event.
GridViewRow gr = (GridViewRow)edit.NamingContainer;//Get the container of the Link Button and Cast it to GridviewRow.
//Get cell value from the GridviewRow
fname = gr.Cells[0].Text;
lname = gr.Cells[1].Text;
addr = gr.Cells[2].Text;
phone = gr.Cells[3].Text;
//Assign it to your textboxes
this.txtFname.Text = fname;
this.txtLname.Text = lname;
this.txtAddress.Text = addr;
this.txtPhone.Text = phone;
}
Thursday, November 6, 2008
Convert String to Enum
Today, I will show you how you can convert the Enum type to a string in .Net. In my demo, I use C#.
Say for example, you have a dropdown where values and texts are list of genders (Male, Female, Gay, Tomboy, Idk),...
and you want to get its preferred partner based on the selected drop down.
public enum Gender
{
MALE,
FEMALE,
GAY,
TOMBOY,
IDK
}
public class Dummy
{
public string GetPreferredPartner(Gender g)
{
if(g == g.MALE)
return "pretty woman";
else if(g == g.FEMALE)
return "handsome guy";
else if(g == g.GAY)
return "macho man";
else if(g == g.TOMBOY)
return "hot mama";
else if(g == g.IDK)
return "macho man";
}
}
//get the selected gender from the drop down
string strGender = this.ddlGender.SelectedValue;
///Here is the conversion of string to an Enumeration
Gender gender = (Gender)Enum.Parse(typeof(Gender), strGender, true);
//the first parameter is the Enum type you want your string to convert to
//the second is the string which will be converted to the specified Enum type
//the third parameter is to determine if the string is case sensitive
That's all, thank you.
-Jygz
jjygot@gmail.com
Tuesday, November 4, 2008
How to use CURSOR in MSSQL
Hi,
Most of us sql lovers might be wondering on how to navigate in every row of a table treating the sql result set like a record set. Although I am sure that for those SQL Server experts, the word Cursor is too common for them and some would say that it would cause too much overhead. But just for the sake of those who don't know what cursor is, I have a basic tutorial for you guys.
-- First I would like to create a temporary table to help us on our tutorial.
Create Table tbl_Temp(
[RowNum] [int] NOT NULL,
[RowValue] [int] NOT NULL
)
Go
-- Next I will insert few records into the newly created table
Insert into tbl_Temp(RowNum,RowValue) values(1,50)
go
Insert into tbl_Temp(RowNum,RowValue) values(2,22)
go
Insert into tbl_Temp(RowNum,RowValue) values(3,11)
go
Insert into tbl_Temp(RowNum,RowValue) values(4,16)
go
Insert into tbl_Temp(RowNum,RowValue) values(5,23)
go
-- Here I need to create a variable that will serve as a storage
-- I want to have it as a varchar so that to avoid casting int values to varchar
Declare @RowNumStorage as varchar(3)
Declare @RowValueStorage as varchar(3)
-- Declare a cursor object that will serve as a pointer for the table tbl_Temp
Declare MyCursor cursor for
select * from tbl_Temp
-- Opening the cursor is important
-- It's like we didn't create any instance of the cursor at all if don't open it
open MyCursor
-- The lines below dictates the cursor to move to the next record
-- by default the cursor's current row location is set to -1
fetch next from MyCursor
into @RowNumStorage,@RowValueStorage
-- Check the row status of the cursor if it is not in the last row
while @@Fetch_Status =0
begin
-- Here I just need to show some displays to test if the cursor is really moving
-- I tried to check every row if the value is an ODD or EVEN number.
if((@RowValueStorage%2)=1)
begin
print 'RowNumber: ' + @RowNumStorage + ', Value:' + @RowValueStorage + ' is an ODD number '
end
else
begin
print 'RowNumber: ' + @RowNumStorage + ', Value:' + @RowValueStorage + ' is an EVEN number '
end
-- I need to call the fetch in order to loop through the record
FETCH NEXT FROM MyCursor
into @RowNumStorage,@RowValueStorage
end
-- finally I need to close the cursor and dispose it
close MyCursor
deallocate MyCursor
Friday, October 24, 2008
JavaScript for applying event for specific class of HTML Elements
Commonly, when we apply event for an HTML Element, we are going to create a function first then put it to function attribute to the html element, in order to trigger the event. Example of this: Assumed that you created a function named PopupHello() that will simply display an alert box with the world "hello" on it. Traditionally, in order to trigger the event, you will put this function inside
the function attribute of a specific html element:
<a href='javascript:void(0)' onclick='PopupHello()'>
That's fine, it works well. But, what if you have the same element in different pages that will do the same function. So, you will have to put the onclick='PopupHello()' for each element, which is for me, it's inappropriate and is costly, because it will add an additional size to your hard drive (or anywhere else..) everytime you add the same element.
Solution for that, is to add a class name for each element that has the same functionality, and during the loading of your website, get all the elements with the same class name and add the function to that class name. I provide the code below to show you how it's done. Just read the comments to understand how it works.
The Code:
<html>
<head>
<script type='text/javascript' language='javascript'>
//this function will get all elements
//in a specific tag passed to this
//if * is passed, it means all the tags
//inside the html
function getDocumentElements(tag)
{
return document.getElementsByTagName(tag);
}
//this is the function that will assign a specific function
//to the click function of a tag within the class
function assignFunction(paramTag, paramClass, paramFunctionName)
{
//first, is to get the elements under a tag
//passed "*" to get all elements regardless what tag
var docElements = getDocumentElements(paramTag);
//loop through each element
for(var i=0; i < docElements.length; i++)
{
//check if the element is under the specific class
if(docElements[i].className == paramClass)
//add the function to the onclick event of the element
docElements[i].onclick = function() {
//this will trigger when this element is clicked
var func = new Function(paramFunctionName);
func();
};
}
}
function PopupHello()
{
window.alert('Hello');
}
function doB()
{
window.alert('Event coming from Class B element');
}
//during window loads
window.onload = function() {
//assign PopupHello() function to any elements
//that belongs to class classA
assignFunction("*","classA", "PopupHello()");
//assign doB() function to anchor elemens (anchor tag <a>)
//that belongs to class classB
assignFunction("a","classB", "doB()");
}
</script>
<title>JavaScript</title>
</head>
<body>
<img class='classA' src='imgA.gif' alt='Class A Image'/> <br /><br />
<img class='classB' src='imgB.gif' alt='Class B Image' /><br />
<a class='classA' href='javascript:void(0)'>Class A - anchor tag</a> <br />
<a class='classB' href='javascript:void(0)'>Class B - anchor tag</a> <br />
<span class='classA'>Class A - span tag</span> <br />
<a class='classC' href='javascript:void(0)'>Class C - anchor tag</a>
</body>
</html>
All elements under class classA will display an alert box saying 'hello'.
classB elements will alert 'Event coming from Class B element'.
And classC will do nothing.
If you will add new element, for example an another anchor tag for classA. You will
simply put the attribute class then attribute value to classA (hence, class="classA").
And, if you want to add a clicked event for other element like for example class classC then anchor tag.
Simply put this inside the onload function: assignFunction("*","classC", "NameOfFunctionForClassC()");
That's all. Thank you.
-Jygz
jjygot@gmail.com
Wednesday, October 22, 2008
How to use the while loop using sql server
To start with the discussion we need a counter variable with an int DataType that would define the limit to where the loop will stop. In my case I named my counter variable as TotalMonths and
assigned it with a value of 12.
set @TotalMonths = 12
-- The While statement is almost the same as the usual programming
-- concept for the while statement. All we need is the logic as to how the
-- loop takes place.
-- In my case I wanted to begin my loop by stating that TotalMonths should be
-- greater than zero before it executes the loop..
While @TotalMonths>0
-- We need to have the begin and end statement after the condition in order to
-- set the scope of the while loop. Hence, if we try to remove the begin/end in the loop,
-- we will notice that the query will have an infinite loop.
begin
-- Here we create the statement that we wanted to do if the condition of the
-- while statement is true.
print datename(mm,(dateadd(mm,-@TotalMonths,(1))))
-- The most important thing on the while loop, is to create a loop iterator to avoid
-- infinite loops.
set @TotalMonths = @TotalMonths - 1
end
Script:
Declare @TotalMonths as int
set @TotalMonths = 12
While @TotalMonths>0
begin
print datename(mm,(dateadd(mm,-@TotalMonths,(1))))
set @TotalMonths = @TotalMonths - 1
end
This results:
January
February
March
April
May
June
July
August
September
October
November
December
.Net Equivalent of PHP's implode and explode function
Lots of developers from PHP who study/migrate to ASP.Net have problems figuring out how would they implode an array of strings, or explode a string to array. Like me, this situation came out during my study in ASP.Net, I wondered what was the equivalent of PHP implode and explode function in .Net. And then I found out, that in .Net you can achieve this using the .Net's built-in string functions: Join function for implode, and string Split function for explode. To illustrate more, I make a sample code as shown below:
Type rest of the post here
///Assumed that you have two labels for display: lblColors, lblFruits
//****IMPLODE/JOIN****\\
//sample string of colors
string[] arrColors = {"red","orange","yellow","green","blue","indigo","violet"};
//implode/join the colors array using "and" and store it to a string variable
string strImplodedColors = String.Join(" and ", arrColors);
//display the imploded/joined to the colors label
this.lblColors.Text = "The colors of the rainbow are: " + strImplodedColors;
//****EXPLODE/SPLIT****\\
//sample string for comma-separated fruits
string strFruits = "avocado, apple, mango, grapes, banana";
//separator for the string
char[] separator = {','};
//explode/split the string and store it to a string array
string[] arrFruits = strFruits.Split(separator);
string strFavFruitDisplay = "Below are my top favorite fruits:
";
int i = 1;//iterator for counting display
//loop or iterate for each string in the exploded string
foreach(string strFruit in arrFruits)
{
//add each fruit to the display string
strFavFruitDisplay += i.ToString() + ". " + strFruit + "
";
i++;
}
//display the favorite fruits
this.lblFruits.Text = strFavFruitDisplay;
The above code is C#, if you want a VB version of it, just go to this URL: http://www.developerfusion.com/tools/convert/csharp-to-vb/
copy the code and convert it. It will allow you to easily convert C#.Net codes to VB.Net and vice versa.
Try it!
Better JavaScript for Numeric Only Input in text box
Sometimes, you will meet a scenario where you will just allow the user to input only numbers in a text field in your web page.
Examples are:
1. text field for quantity of a product to be purchased
2. text field for order number.... and more
Although, this can be done in the server-side process, but it's much better to do this in the client side (like checking if the key pressed is a number) for better user-experience. Because doing this in the server side will reload your page back and cost time and process. Doing this in the client side, is more user-friendly, there is an immediate checking, everytime the user presses a key in the keyboard the client javascript will check if that key is a valid number without interrupting the user on what he/she's doing.
To achieve this, we are going to create a JavaScript function then apply it to our text field.
Assumed that we have the following html code(pure html):
<html>
<head>
<title>Numeric Only in Text Input</title>
</head>
<body>
<form>
Enter Number: <input type='text' />
<form>
</body>
</html>
What To Do:
1. Place the following code: inside the head tag of your html
< script type='text/javacript' language='javascript'>
//function for allowing numeric only
function NumericOnly(e)
{
//gets the numeric code of the key pressed
var charCode = (e.which) ? e.which : e.keyCode
//checks if the cod is greater than 31 like the "space" which is 32,
//and it is less than 48 which is "0" or greater than "57" which is 9
//then do not allow it
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;//key pressed is not allowed
return true;//key pressed is allowed
}
</script>
2. Apply the function to the key press event of the text field you want to allow numeric only inputs.
thus:
<input type='text' onkeypress='return NumericOnly(event);' />
Final Output:
<html>
<head>
<script type='text/javascript' language='javascript'>
//function for allowing numeric only
function NumericOnly(e)
{
//gets the numeric code of the key pressed
var charCode = (e.which) ? e.which : e.keyCode
//checks if the cod is greater than 31 like the "space" which is 32,
//and it is less than 48 which is "0" or greater than "57" which is 9
//then do not allow it
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;//key pressed is not allowed
return true;//key pressed is allowed
}
</script>
<title>JavaScript's Numeric Only in Text Input</title>
</head>
<body>
<form>
Enter Number: <input type='text' onkeypress='return NumericOnly(event);' />
</form>
</body>
</html>
The key part in the code is :
if (charCode > 31 && (charCode <> 57))
What it does are:
1. It will disallow input which is not valid, it only allows numeric code less than 31( that includes: backspace, enter, arrow keys, delete key, function keys, tabs,...)
2. It only allows numeric code not less than 48 and not greater than 57, less than 48 codes are ( the symbols or operators like +, -, / *, &......), codes greater than 57 are the (special characters like colon:, semicolon;, <,=,?,{,},~.....) , alpha characters(ABCD....abcd...)
Numbers numeric codes range from 48 - 57.
Visit this website to understand more: http://ascii-table.com/
That's all! Try it now...
Have a nice day.
Jygz
jjygot@gmail.com