Is it possible to show empty label value if the value of a column used for date or time is null?

Donald Symmons 3,066 Reputation points
2023-03-13T13:41:43.36+00:00

I have column for Name, Date and another one for Time. If the values of date and Time columns are null or empty, how do I get to still show the label value in null data value?

Is this Possible? please how can I do that?. Here is what I mean in the table.

IdtypeEventNameDatedTimedLocation1EventArts Exhibition13-Mar-2303:00PM2 king Avenue2Visit permitVisitor8 plane str. From the table above, the type, Event has value in Dated and Timed columns, while Visit permit does not have any value in the Date and the timed columns.

My Code to display from database onto the label controls

string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                    using (SqlConnection con = new SqlConnection(connectionString))
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand
                        {
                            CommandText = "SELECT * FROM TicketTable WHERE EventName = '" + Session["index"] + "'",
                            Connection = con
                        };
                        SqlDataAdapter sda = new SqlDataAdapter();
                        DataSet ds = new DataSet();
                        sda.SelectCommand = cmd;
                        sda.Fill(ds, "detail");
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            Title.Text = ds.Tables[0].Rows[0]["EventName"].ToString();
                            datelbl.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["Dated"]).ToLocalTime().ToString("MMM d, yyyy");
                            timelbl.Text = ds.Tables[0].Rows[0]["Timed"].ToString();
                            venuelbl.Text = ds.Tables[0].Rows[0]["Location"].ToString();
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Record not found');", true);
                        }
                    }

Developer technologies | .NET | Other
Developer technologies | ASP.NET | Other
Developer technologies | C#
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,191 Reputation points Microsoft External Staff
    2023-03-14T03:10:50.8933333+00:00

    Hi @Donald Symmons,

    You can use the following code:

    datelbl.Text = ds.Tables[0].Rows[0]["Dated"] == DBNull.Value ? (string)null : Convert.ToDateTime(ds.Tables[0].Rows[0]["Dated"]).ToLocalTime().ToString("MMM d, yyyy");

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


3 additional answers

Sort by: Most helpful
  1. Michael Taylor 60,326 Reputation points
    2023-03-13T14:14:48.2433333+00:00

    Database NULLs are represented as DbNull in ADO.NET. If you expect columns to be nullable you have to handle that case.

    I'm not clear on what you want to display when they are null but I suspect you at least don't want it to crash.

    if (!ds.Tables[0].Rows[0].IsNull("Dated"))
       datelbl.Text =  Convert.ToDateTime(ds.Tables[0].Rows[0]["Dated"]).ToLocalTime().ToString("MMM d, yyyy");
    else
       datelb1.Text = "None";
    if (!ds.Tables[0].Rows[0].IsNull("Timed"))
       timelbl.Text = ds.Tables[0].Rows[0]["Timed"].ToString();
    

    I would also encourage you to use the strongly typed helper methods of DataRowExtension to simplify your code.

    sda.Fill(ds, "detail");
    var row = ds.Tables.OfType<DataTable>().FirstOrDefault().Rows.AsEnumerable();
    if (row != null)
    {
       Title.Text = row.Field<string>("EventName");
       datelbl.Text = !row.IsNull("Date") ? row.Field<DateTime>("Dated").ToLocalTime().ToString("MMM d, yyyy") : "None";
       timelbl.Text = !row.IsNull("Timed") ? row.Field<string>("Timed") : ""; 
       venuelbl.Text = row.Field<string>("Location");
    }
    else
    {
       ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Record not found');", true);
    }
    

    I'm guessing on your datatable's types though.

    0 comments No comments

  2. Sreeju Nair 12,666 Reputation points
    2023-03-13T14:21:15.4733333+00:00

    You can check whether the column contains null value by

    if(ds.Tables[0].Rows[0]["Dated"] != DBNull.Value)
    {
        datelbl.Text = Convert.ToDateTime(ds.Tables[0].Rows[0]["Dated"]).ToLocalTime().ToString("MMM d, yyyy");
    }
    else
    {
        datelbl.Text = "Date in empty";
    }
    

    However by taking a glance at your code, there are several improvement opportunity.

    1. You are doing concatenation to build your query, this can lead to SQL Injection attacks. So shift to parameterized queries.
    2. Try to use Entity Framework as it will be easier.
    3. In the provided code, you are using SQLDataAdapter, but I could n't find any data binding code. SQLDataAdapter was used for doing bidirectional update between the dataset and your database. Read more https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldataadapter?view=dotnet-plat-ext-7.0 However, based on the code you are only reading data from the database, then it is better to use SQLDataReader
    4. https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader?view=dotnet-plat-ext-7.0
    5. https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/retrieving-data-using-a-datareader

    In SQLDataReader, there is a method to check whether the value is null. https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqldatareader.isdbnull?view=netcore-1.1

    Hope this helps


  3. Albert Kallal 5,586 Reputation points
    2023-03-15T01:29:09.53+00:00

    Lots of answers here.

    Might consider a "helper" converter.

    So,

                    datelbl.Text =  fDate(dt.Rows[0]["VisitDate"]);
    
    and
    
    
            string fDate(object dt)
            {
                if (DBNull.Value.Equals(dt))
                {
                    return "";
                }
    
             return Convert.ToDateTime(dt).ToLocalTime().ToString("MMM d, yyyy");
            }
    
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.