.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Help: Too many lines of code to achieve a simple goal: keep my NULL SQL values...

Posted By:      Posted Date: August 27, 2010    Points: 0   Category :ASP.Net

Hello all

What is the best way (best practice) to preserve my NULL SQL values in the database
during an insert/update operation (without receiving cast invalid errors)?
Also, how to display a string 'n/a' when a sql value is NULL?

My project is using FormView with Edit/Insert templates and classes to represent my tables

Goal1....: display 'n/a' when there are NULL SQL values in the database
Solution1: I am using ISNULL(field,'') in my store procedure for SELECT statements

Goal2....: if the fields are 'n/a', then save them back in the database as NULL
Solution2: on my insert/edit methods I am having to check the values being passed, i.e:

cmd.Parameters.Add(new SqlParameter("@scope", SqlDbType.NVarChar, 50));

if (item.Scope == "n/a")
 cmd.Parameters["@scope"].Value = DBNull.Value;
 cmd.Parameters["@scope"].Value = item.Scope;

Not to mention that for SQL DateType fields when you use ISNULL(field,'') the return string is '1/1/1900 12:00:00 AM'
and I have to change the field value in every field that represents a date, i.e:

protected void FormView1_DataBound(object sender, Sy

View Complete Post

More Related Resource Links

Wicked Code: Silverlight Page Turning Made Simple


As we'll show, with just a few lines of JavaScript you can build a general-purpose framework for incorporating page turns into Silverlight 1.0 apps.

Jeff Prosise

MSDN Magazine May 2008

Secure Habits: 8 Simple Rules For Developing More Secure Code


Never trust data, model threats against your code, and other good advice from a security expert.

Michael Howard

MSDN Magazine November 2006

Simple Captcha Code in Javascript

The article Simple Captcha Code in Javascript was added by miya2008 on Tuesday, June 29, 2010.

Here I create a Cptcha Code With JavaScriptStep 1:->In the (.aspx) page we write the following Code:->%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>!DOCTYPE

How to deal with NULL values in a SQL table


 Hi all

In order to add/update/delete data from a table I build 2 classes: 1 class containing all the table fields and another class with methods to add/insert/update/delete records. I am learning how to avoid errors when your table must use SQL NULL values. One error is when I call my UPDATE method (see below):

  public void UpdateItem(OcItemConstraintDetails item)
  SqlConnection con = new SqlConnection(connectionString);
  SqlCommand cmd = new SqlCommand("ItemConstraints_Update", con);
  cmd.CommandType = CommandType.StoredProcedure;

  cmd.Parameters.Add(new SqlParameter("@itemConstraintId", SqlDbType.Int, 4));
  cmd.Parameters["@itemConstraintId"].Value = item.ItemConstraintId;

  cmd.Parameters.Add(new SqlParameter("@path", SqlDbType.NVarChar, 150));
  cmd.Parameters["@path"].Value = item.Path;

if you watch the SQL profiler trace you will see that I am passing a value of 'default' ;so that causes me problems.

exec ItemConstraints_Update @itemConstraintId=1,@path=default

With that said, what are the best practices when your SQL table accepts NULL values and when:
- you are passing an empty value to your stored procedure;

Use DB query result to generate Jquery required lines of code



I 'm gonna query database for photo records. each record include "photo path" where imagesURL  stored in string format

 I Choses my favorite Juqery plugin to show images. Plugin needs some lines of code like below.

How could I  generate these lines

$(function() {
sleep: 2,
fade: 1
}, [
{ src: 'picture1.jpg' },
{ src: 'picture2.jpg' },
{ src: 'picture4.jpg' }

Dropdownlist appears to be null in code behind


I have a weird problem...

I have a web part form, with one of the dropdownlist, when referenced in code behind, happes to be null.

Common.bindMultiChoices(ddlPly4, oEnquiriesList, "Ply 4 Type (Paper)", "Select Ply 4", null); 

But at front user control file, I do have:

<tr><td><asp:DropDownList ID="ddlPly4" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlPly4_OnSelectedIndexChanged" /&


HI. I NEED LITTLE HELP. I have values 1000,2000,3000, wich located in numValue. Now I have sql table CUSTOM1 with column CUSTOM_ID where located numbers 1000,1001,2005,2006 .. Now if I choose( NumValue == 1000) go to sql table and find Maximum number wich begin with 1000 and add 1 = Result must be 1002 there is my code what change I must do in order to receive the num max + 1?       DataTable dt = new DataTable();         SqlConnection con = new SqlConnection("Data Source=DYS-PC;Initial Catalog=Veolia;Integrated Security=True");         SqlCommand cmd = new SqlCommand("Select Count(*) " + "FROM [MHGROUP].CUSTOM1 " + "WHERE CUSTOM_ALIAS = '" + comboBox2.Text + "'", con);         SqlDataAdapter sqlDa2 = new SqlDataAdapter();         sqlDa2.SelectCommand = cmd;         sqlDa2.Fill(dt);      

InfoPath repeating table Copy values from above row without Code

Hi, I have situation, where I want to copy the values from the above row to the newly created row in a Repeating table. Ex. I have a repeating table with 3 columns ID-Name-FileName. When I enter a data like 1-Customer1-File1.zip and hit "Insert new row", the new row should automatically populate the values of the above row. How can I do it without .Net code. Regards,

SSRS Report based on SSAS Cubes doesn't show NULL values correctly

I have a SSRS report which is based on an SSAS Cube. In the Cube the formating of numeric fields that NULL values are properly shown as NULL values. In the Cube Browser and Excel this is shown correctly. However when I design the report already the query against SSAS shows these fields as "0" instead of NULL. Is there a way to fix this or is this a bug ?  

Gridview RowCommand Event returning null values

HiI'm trying to retreive values entered by users in the textboxes in the footer of the gridview and insert these values into another sql table.My code is as follows :-protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)    {       if(e.CommandName.Equals("addnew"))       {                       TextBox t1 = (TextBox)GridView2.FooterRow.FindControl("tfrm");            string frm = t1.Text;            TextBox t2 = (TextBox)GridView2.FooterRow.FindControl("tsub");            string sub = t2.Text;            string cmd = "insert into suggestions values('" + frm + "','" + sub + "','c','c')";            con.Open();            SqlCommand com = new SqlCommand(cmd,con);            int a = com.ExecuteNonQuery();&n

Comparing Null Values(from variable) in SSIS

Hi All I need to create a script that checks to see if a variable value is NULL, if it is then it executes the next SQL Task and if not then the package has finished. I have this in a SQL 2000 DTS package script: Function Main() If isnull(DTSGlobalVariables("NextLoadDate")) Then Main = DTSStepScriptResult_DontExecuteTask Else Main = DTSStepScriptResult_ExecuteTask End if End Function As you can see, all I want to do is check to see if a variable is null then don't execute the next task. But i cannot get it to work in a SQL 2005 SSIS package, so far I have created a script and come up with the following: Public Sub Main() If Dts.Variables("NextLoadDate").Value.ToString <> "" Then Dts.TaskResult = Dts.Results.Success Else Dts.TaskResult = Dts.Results.Failure End If End Sub Any Ideas? Thanks BigGopher

How do I get column values in Sharepoint designer so I can use them as a variable in code block?

The code below is in my EditForm.aspx and it works but instead of it outputting "This is just a test!" I need get a number that is stored in a column named Phone Number that has 5555555555 stored in it and have the line that says TD2.innerHTML = "This is just a test!"; ouput what ever number is stored in the Phone Number column. Here is the code that is in my EditForm.aspx <script type="text/javascript">function DisplayItemID(){       var TD1 = document.createElement("TD");       TD1.className = "ms-formlabel";       TD1.innerHTML = "<h3 class='ms-standardheader'>Test</h3>";       var TD2 = document.createElement("TD");       TD2.className = "ms-formbody";       TD2.innerHTML = "This is just a test!";       var IdRow = document.createElement("TR");       IdRow.appendChild(TD1);       IdRow.appendChild(TD2);       var ItemBody = GetSelectedElement(document.getElementById("idAttachmentsRow"),"TABLE").getElementsByTagName("TBODY")[0]; 

Comparing columns with NULL values--Merge says unmatched when data is matched.

I found the article below describing this same issue with the Oracle merge statement.  It also described a work-around:    http://searchoracle.techtarget.com/tip/Merging-datasets-with-NULL-values I have been unable to find a solution to this issue for SQL Server 2008.  I am trying to do basic ETL from Staging table to a Type II dimension table in a Data Warehouse.  I am using the Merge statement with the Unique key minus the modification date as my merge key list.  I have a handful of columns (in both Staging and the DW) containing nulls in my merge key list.  I have tried the ISNULL function and the ANSI_NULL db option (OFF) with no success.  When I put zeros in the null columns, it works as expected.  I am about to try separate INSERT and UPDATE statements, but I fear that the NULL comparison issue will bite me there with the JOIN statement.  Has anyone else experienced this?  NULL values are valid in our Data Warehouse.  How can I make T-SQL handle them? Thank you for your help, Jesse

Problems querying XML data with null values

If the tags have "xsi:nil" in them, then my query failes with a "XML parsing: line [x], character [x], undeclared prefix" error.  So my question is how to get the query to handle or ignore those tags with "xsi:nil" embedded in them.  So specifically, the first SQL query below is successful, and the second one fails with the aforementioned error.  Any comments appreciated, thanks. -- Declare XML variable DECLARE @data XML; -- Element-centered XML SET @data = N'<data> <customer> <id>1</id> <name>Allied Industries</name> </customer> <customer> <id>2</id> <name>Trades International</name> </customer> </data>'; -- Using the query() method SELECT T.customer.query('id').value('.', 'INT') AS customer_id, T.customer.query('name').value('.', 'VARCHAR(20)') AS customer_name FROM @data.nodes('data/customer') AS T(customer); Returns: 1 Allied Industries 2 Trades International ================== -- Declare XML variable DECLARE @data XML; -- Element-centered XML SET @data = N'<data> <customer> <id>1</id> <name>Allied Industries</name> <fax xsi:nil="true" /> </customer> <customer> <id>2</id> <name>Trades International</name> <fax xsi:nil=&quo

Create unique constraint on a column which has null values

Hi All, I have a table suppose 'Temp' having one of the column as 'ColA' which has some null values as well as non null values. Now i have a requirement to create a unique constraint on it. We have tried but couldnt do it.Apart from having a trigger on insert and update statements is there any other alternate. Can any one please help me on this. Thanks & Regards, Srikanth  
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend