Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2046
  • Last Modified:

DataRow substring works fine unless there is a null value.

I am trying to convert a datarow value to a substring and it works fine unless the value of the datarow is null.  I've tried several if statements and none seem to be working.

Here's my code to the substring
foreach(DataRow dm in dt.Rows)
{
dm["mobile"]=dm["mobile"].ToString().Substring(4);

}

My datatableresults display in a datagrid which will always have some of these fields with data and some without.  

if there isn't any value in the row I get this error
Length cannot be less than zero. Parameter name: length

Any ideas?
0
JoanHerrick
Asked:
JoanHerrick
  • 3
  • 3
  • 2
1 Solution
 
vo1dCommented:
foreach(DataRow dm in dt.Rows)
{
  if(dm["mobile"] != null)
  {
    dm["mobile"]=dm["mobile"].ToString().Substring(4);
  }
}
0
 
JoanHerrickAuthor Commented:
Doesn't work.  Same error.  Here's more of my code in case that helps.  Oh, thanks for your speedy response!

            public DataSet FindUsers(string sFilter, string[] columns, string path, bool useCached)
            {
                  
                  HttpContext context = HttpContext.Current;
                  DataSet userDS = (DataSet)context.Cache[sFilter];
           
                  if((userDS == null) || (!useCached))
                  {
                         
                        DirectoryEntry deParent = new DirectoryEntry("ad server string");
                        deParent.Username = @"username";
                        deParent.Password = "password";
                        deParent.AuthenticationType = AuthenticationTypes.Secure;
           
                        DirectorySearcher ds = new DirectorySearcher(
                              deParent,
                              sFilter,
                              columns,
                              SearchScope.Subtree
                              );

                        ds.PageSize = 1000;
           
                        using(deParent)
                        {
                              
                              userDS = new DataSet("userDS");
                              DataTable dt = userDS.Tables.Add("users");
                              DataRow dr;  
                              
                              foreach(string prop in columns)
                              {
                                    dt.Columns.Add(prop, typeof(string));
                              }

                              using (SearchResultCollection src = ds.FindAll())
                              {
                                    foreach(SearchResult sr in src)
                                    {
                                          dr = dt.NewRow();
                                          foreach(string prop in columns)
                                          {
                                                if(sr.Properties.Contains(prop))
                                                {
                                                      dr[prop] = sr.Properties[prop][0].ToString();
                                                }
                                          }
                                          dt.Rows.Add(dr);
                                          
                                    }
                                                                  
                                          foreach (DataRow dm in dt.Rows)                                           
                                          {
                                                if(dm["mobile"]!=null)
                                                
                                                {
                                                      dm["mobile"]=dm["mobile"].ToString().Substring(4);
                                                }
                                          }                                                                                                                                                       
                                    
                              }
                         
                        }
                  
                        context.Cache.Insert(sFilter, userDS, null, DateTime.MaxValue, TimeSpan.FromSeconds(180));
                  }
                  return userDS;
            }
            
            private void Page_Load(object sender, System.EventArgs e)
            {
            TextBox1.Attributes.Add("onkeydown", "KeyDownHandler"+base.PortletID.ToString()+"('Button1')");            

      
            }
      
      
            private void Button1_Click(object sender, System.EventArgs e)
            {
                  string qry = String.Format("(&(objectCategory=person)(|(givenName={0}*)(sn={0}*)))", TextBox1.Text);
                  string[] columns = new string[]{"givenName", "sn", "cn", "department", "telephoneNumber", "mobile"};
                  
                  string ldapPath = "ad server string";

                  DataSet ds = FindUsers(qry, columns, ldapPath, true);
                         
                  DataGrid1.DataSource = ds;
                  DataGrid1.DataBind();
            }
            }
      }
0
 
vo1dCommented:
what is the exact error message and in which line is the exception thrown?
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
topdog770Commented:
I've seen, and used a couple different methods to handle this and still not sure that there isn't a better way to do it.

1)  

foreach(DataRow dm in dt.Rows)
{
  try
  {
     dm["mobile"]=dm["mobile"].ToString().Substring(4);
   }
   catch
  {  // value was null
     dm["mobile"] = "empty or how ever you want to handle it";
  }
}

2)   dm["mobile"].Equals(DBNull.Value) ? "" :  dm["mobile"].ToString().Substring(4);


3) In VS 2005 you can do if(!String.IsNullOrEmpty( dm["mobile"])) {      dm["mobile"]=dm["mobile"].ToString().Substring(4); }
// im not at comp with 2005 so hopefully I have the syntax correct

If you are using / were using a typed dataset, you can define values that indicate a null value, and then check for that null indication value.

I've used this idea quite a bit.

      #region public sealed class Null

      public sealed class Null
      {
            public static readonly int Int = -1;
            public static readonly double Double = -1000000;
            public static readonly string String = "StringIsNull";
            public static readonly string Date = "01/01/1900";
            public static readonly decimal Decimal = -0.1m;

            private Null()
            {

            }
      }
      #endregion // public sealed class Null



then you can do something like...

If dm["mobile"].Equals(Null.String)
0
 
vo1dCommented:
i would recommend not using the try catch block solution without any exception evaluation.
the rest is fine ;)
0
 
topdog770Commented:
Valid point, thanks! Didn't catch that :P... should have just copy and pasted something in :)
0
 
JoanHerrickAuthor Commented:
Thanks experts - can you explain about the exception evaluation?
0
 
topdog770Commented:
The try / catch blow above just assumes that an occurring exception was because of a null.

If there were memory problems, dataset issues or other malfunctions, in the code snippet above, none of them are
accounted / checked for.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now