December 2009


I found a tool where you can paste your VB.NET code to get it’s equivalent c# code.

Check out the link

Suppose we have a asp menu like the one shown below, and we want to hide all items except the first item, the code is as follows:

<asp:Menu
        id=”MnuApplication”
        Orientation=”Horizontal”
        StaticMenuItemStyle-CssClass=”tab”
        StaticSelectedStyle-CssClass=”selectedTab”
        CssClass=”tabs”
        OnMenuItemClick=”MnuApplication_MenuItemClick”
        Runat=”server”>
        <Items>
        <asp:MenuItem Text=”Application” Value=”0″ Selected=”true” />
        <asp:MenuItem Text=”Environment” Value=”3″ />
        <asp:MenuItem Text=”Focal Point” Value=”2″ />
        <asp:MenuItem Text=”Vendor” Value=”1″ />
        </Items>   
    </asp:Menu>

There is no option to hide menu items, we have to remove them through coding, so, if we want to hide all items except the first one, that is “Application”
for (int i = 0; i < MnuApplication.Items.Count; i++)
{
    if (MnuApplication.Items.Count > 1)
    {
       if (!MnuApplication.Items[i].Text.Equals(“Application”))
        {
            MnuApplication.Items.Remove(MnuApplication.Items[i]);
            i = 0;
         }
      }
}

To add items to a menu we do the following,

MenuItem mnuVendor = new MenuItem();
mnuVendor.Text = “Vendor”;
mnuVendor.Value = “1”;
MnuApplication.Items.Add(mnuVendor);

We use views within a   multiview to display the content of each menu. we can set the index of a particular view using ActiveViewIndex on click of a menu  :

protected void MnuApplication_MenuItemClick(object sender, MenuEventArgs e)
{
  int index = Int32.Parse(e.Item.Value);
  MultiView1.ActiveViewIndex = index;
}

 

To to validation checking or marking foelds mandatory while saving data, the below code can be used, here txtVendorName is the name of the control

function trim(strText) { while (strText.substring(0,1) == ‘ ‘) { strText = strText.substring(1, strText.length); } while (strText.substring(strText.length-1, strText.length) == ‘ ‘) { strText = strText.substring(0,strText.length-1); } return strText; }

function MandatoryCheck()
{
  var VendorName = document.getElementById(‘<%= txtVendorName.ClientID %>’); 
  if(trim(VendorName.value) == ”)
  {
      alert(“Please enter a Vendor name.”);
      return false;
  }
 }

Sometimes we might just need to add values to a dropdownlist which does not change frequently, hence listitem can solve the problem. Below is an example of populating dropdown list using listitem through coding.

Suppose name of th dropdownlist is drpChooseStatus

List<System.Web.UI.WebControls.ListItem> status = new List<System.Web.UI.WebControls.ListItem>(); status.Add(new ListItem(“In Progress”, “1”)); status.Add(new ListItem(“To be added”, “2”)); status.Add(new ListItem(“Completed”, “3”));
drpChooseStatus.DataSource = status;
drpChooseStatus.DataBind();

Sometimes if a table has many columns, inserting data can be tiresome as you have to write many input parameters from your  application, a smart way to handle this would be to pass the values as xml and use openxml to save data, below is an example:

Define a datatable with all the columns you need to save and add it to a Dataset, something like the one showed below

 DataSet dsAddServerDetails = new DataSet();
DataTable dtServer = new DataTable(“Server”);
dtServer.Columns.Add(“Server_Name”, Type.GetType(“System.String”));
dtServer.Columns.Add(“OS”, Type.GetType(“System.String”));
dtServer.Columns.Add(“Server_Type”, Type.GetType(“System.String”));
dtServer.Columns.Add(“CreatedBy”, Type.GetType(“System.String”));
dtServer.Rows.Add(//Insert logic to add row…);
dsAddServerDetails.Tables.Add(dtServer);

//While Saving
ArrayList arrList = BusinessLayer.GetData(dsAddServerDetails);
if (arrList.Count > 0)
{
 string strServerId = arrList[0].ToString();
}

//BusinessLogic and DataAccess Layer logic

public static class BusinessLayer
    {
        public static ArrayList GetData(DataSet ds)
        {
            int intRetValue;
            ArrayList arrRetVal = new ArrayList();
            try
            {
                arrRetVal = DataAccessLayer.GetData(ds);
            }
            catch (Exception ex)
            {
                throw ex;            }
            return arrRetVal;
        }
}

public static class DataAccessLayer
{
public static ArrayList GetData(DataSet ds)
        {
            int intRetValue;
            ArrayList arrRetVal = new ArrayList();
            try
            {
                Database db = DatabaseFactory.CreateDatabase();
                DbCommand command = db.GetStoredProcCommand(“SaveServer”);
                db.AddInParameter(command, “@ServerDetails”, DbType.Xml, ds.GetXml());
                db.AddOutParameter(command, “@ServerId”, DbType.Int32, 4);

                intRetValue = db.ExecuteNonQuery(command);
                if (intRetValue == -1)
                {
                    int intServerId = Int32.Parse(db.GetParameterValue(command, “@ServerId”).ToString());
                    arrRetVal.Add(intServerId);
                }
            }
            catch (Exception ex)
            {
                throw ex;            }
            return arrRetVal;
        }
}

//Stored Procedure

ALTER PROCEDURE [dbo].[SaveServer]
 — Add the parameters for the stored procedure here
 @ServerDetails  xml,
 @ServerId int OUTPUT
AS
BEGIN
EXEC sp_xml_preparedocument @hDoc OUTPUT,@ServerDetails
BEGIN TRANSACTION
 INSERT INTO tblServer(
 Server_Name,
 OS,
 Server_Type,
 CreatedBy)
 SELECT
 Server_Name,
 OS,
 Server_Type,
 CreatedBy
 FROM OPENXML(@hDoc, ‘NewDataSet/Server’,2)
 WITH (
 Server_Name varchar(50),
 OS varchar(50),
 Server_Type varchar(50),
 CreatedBy datetime)
 SET @ServerId = @@IDENTITY
 SELECT @ServerId
 IF @@ERROR <>0
  BEGIN
   ROLLBACK TRANSACTION
   RAISERROR(‘Error Inserting Server items!’,11,1) with NOWAIT, SETERROR;
   RETURN
  END
 ELSE
  BEGIN

In the previous post where I showed how to bing a dropdown to a Enumeration. Here, I will show how to get the enum value of a string and make it the selectedindex of a dropdown list.

Suppose I have a enumeration like the one showed below:

public static class BusinessLogic
{
 public enum SetEnvironment
 {
    Development = 1,
    Testing = 2,
    Staging = 3,
    Production = 4
 };
}

If I have a dropdown DropDownList1 whose selecteditem needs to be “staging” at run time, I can do the below procedure to convert a string to a enum value:

string strSelect = “Staging”;
/*ClassName.EnumName EnumInstance = (ClassName.EnumNme)Enum.Parse(typeof(ClassName.EnumName), selectedtext);*/
BusinessLogic.SetEnvironment EnumInstance = (BusinessLogic.SetEnvironment)Enum.Parse(typeof(BusinessLogic.SetEnvironment), strSelect);
int intEnumVal = (int)EnumInstance;
DropDownList1.SelectedIndex = intEnumVal – 1;

Sometimes we might require to mind dropdowns with some fixed values, in such cases it might not be necessary to bind them with values from database. We can write the values in a enumeration and retrieve the array and bind it with the dropdown. below is an example.

public static class BusinessLogic
{
 public enum SetEnvironment
        {
            Development = 1,
            Testing = 2,
            Staging = 3,
            Production = 4
        };
}

Suppose we have a dropdown named DropDownList1.

So, to populate the dropdown list, the code is as follows:

DropDownList1.DataSource = Enum.GetNames(typeof(BusinessLogic.SetEnvironment));
DropDownList1.DataBind();

Next Page »