Reputation: 1199
I am having a method(C#) in asp.net CodeBehind file. I want to reuse the same method in some other CodeBehind file. How is it possible ? And I want to know whether it is appropriate to do so ?
Lets say I am having a method like this. How to reuse this ?
protected void button_view(object sender, EventArgs e)
{
hdnViewStatus.Value = "0";
EmployeeDLL empDll = new EmployeeDLL();
DataSet ds = empDll.ViewEmployee(Convert.ToInt32(txtEmpId.Text));
if(ds.Tables.Count!=0)
{
lblFirstName.Text = Convert.ToString(ds.Tables[0].Rows[0][1]);
lblLastName.Text = Convert.ToString(ds.Tables[0].Rows[0][2]);
lblMobileNo.Text = (ds.Tables[0].Rows[0][3] == null) ? string.Empty : Convert.ToString(ds.Tables[0].Rows[0][3]);
lblStreetName.Text = Convert.ToString(ds.Tables[0].Rows[0][4]);
lblCity.Text = Convert.ToString(ds.Tables[0].Rows[0][5]);
}
}
Upvotes: 1
Views: 1775
Reputation: 5808
You can create a method with public property which used in whole application. Good to create at common place i.e. in a common class(.cs) file.
You can use some method from abstract class too.
namespace project1
{
public class ClassName
{
public object Method1(string para1,....)
{
}
}
}
`
namespace project1
{
public class ClassName2 : ClassName1
{
public object Method2(string para1,....)
{
enter code here...
}
}
}
` 3. abstract class for abstract method to reuse, please read links
http://msdn.microsoft.com/en-us/library/sf985hc5.aspx
http://www.codeproject.com/Articles/6118/All-about-abstract-classes
Upvotes: 1
Reputation: 2917
The best way to re-use a method is public class or a static class. But, in your case you are using few UI controls such as labels and hidden fields. So, in this case if you need to re-use the same logic (not just the method) you'll have to create a user control with a public property to accept the data set that you are using here. In this user control you'll have your labels and the hidden field.
Here's how you'd create a user control.
Hope this helps you to get going.
Cheers!
Upvotes: 1
Reputation: 2286
buildConnectionString([...]);
namespace mafoster_utility
{
public static class mafoster_utility
{
public static string buildConnectionString( string dataSource, string username, string password, string database )
{
//[...]
}
}
}
Upvotes: 0
Reputation: 10364
If you want to use this event code in the same page code behind file means, then you create a new method and place this code under that method, and call that method wherever you want....
Upvotes: 0