asp.net display datalist containing empty record for new Insert

Hi Experts,

I have a DataList which I would like to use as the template to insert new records to. Unfortunately, when binding the DataList to an empty record, the DataList will not display anything.

Is there some way of getting around this?

Thanks for any advice!
manceAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David H.H.LeeCommented:
mance,
The Datalist will display nothing because datasource is empty. But, to let user know about the empty record status, you can do following steps to get somethings display to user even it remain no data.
eg:
1. place a label underneath your datalist control and set the label text="No records found" and make it visibile="false"
2. After bind the datasource for Datalist, you can use datalistName.item.count to check wheter is >0 or not. If the answer return "0" mean nothing inside your datasource, thus you can set the datalist control to visible="false" and the label for "No records found" to visible="true"

If that not solve your problems, please elobarate your requirement more clearly. This will make me more easy to figure out what you need.

Regards
x_com
0
manceAuthor Commented:
Hi X_com,

Good to see that you're working hard trying to help everyone!

Unfortunately that wasn't what I meant in my question.

I'm using a DataList to display a Form (ie like an Insurance Form) and I want to be able to use the DataList to perform updates AND INSERTS. The Key point being Inserts, because a DataList will not be displayed if the datasource contains no records. What I want to do is have the DataList simply display the form and let the user input a NEW record and insert it into the database.

An example may illustrate the question better.

Let's say you have a new Employee and you want to add he into the database. Currently, there's exists a DataList which allows one to Update existing records. I want to use the current DataList to display the EditItem form (no record attached to it because of course it doesn't exist in the database) and use it to Insert a new record.

Is this possible?

I hope this is clear. Thanks!

Here's a brief outline of my code:

<asp:datalist id="lstLocation" Runat="server" CssClass="GeneralContent">
            <ItemTemplate>
                  <table cellspacing="1" width="100%" cellpadding="1" class="InspectionTable">
                        <tr>
                              <td class="InspectionQuestionCell" colspan=4>
                                    Location - General Information
                              </td>                        
                        </tr>
            ...
      </table>
            </ItemTemplate>
            <EditItemTemplate>
                  <table cellspacing="1" width="100%" cellpadding="1" class="InspectionTable">
                        <tr>
                              <Td>
                                    <%# Container.DataItem("LocationID") %>
                                    :
                              </Td>
                              <TD>
                  ...
            </tr>
                  </table>
            </EditItemTemplate>
      </asp:datalist>



0
David H.H.LeeCommented:
mance ,
Why dont just provide a control to insert the data outsite Datalist control?You only can update data in datalist, not for insert as i know so far about datalist.That's the proper way to use Datalist.

Regards
x_com
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

manceAuthor Commented:
Hi x_com,

Been researching this topic and appears that you're probably right.

The reason why I want to do this is because the Form itself is fairly elaborate and I didn't want to have to do more than was necessary. So essentially the reason is because I'm lazy! (Not always a bad trait to have for a programmer).

Anyway, I have thought of using a Stored Procedure to insert a blank row into the database, then if the user saves the information it would be a quasi-Update of the information. If the user doesn't save then the row would have to be deleted.

But to be honest, I'm not sure it this is less or more work than creating a new form!
0
David H.H.LeeCommented:
Here's my version about what i'm said before

default.aspx
---------------
<%@ Import Namespace="System.Data" %>
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="default.aspx.vb" Inherits="dgFull.Cdefault" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>Datalist Edit Example</title>
            <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
            <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
            <meta name="vs_defaultClientScript" content="JavaScript">
            <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout" bgColor="#ffffff">
            <form runat="server" ID="defaultForm">
                  <h3>
                        <font face="Verdana">DataList Edit Example</font>
                  </h3>
                  <P>
                        Ref:&nbsp;
                        <asp:TextBox id="txtRef" runat="server" Width="82px" Height="24px" BorderStyle="Groove"></asp:TextBox>
                        &nbsp;Item:&nbsp;
                        <asp:TextBox id="txtItem" runat="server" Width="82px" Height="24px" BorderStyle="Groove"></asp:TextBox>
                        Price:
                        <asp:TextBox id="txtPrice" runat="server" Width="82px" Height="24px" BorderStyle="Groove"></asp:TextBox>
                        &nbsp;
                        <asp:Button id="btnInsert" runat="server" Text="Insert" BorderStyle="Groove" Width="65px" Height="24px"></asp:Button>
                  </P>
                  <p>
                  </p>
                  <asp:datalist id="DataList1" OnEditCommand="DataList_EditCommand" BorderWidth="1px" CellPadding="3"
                        BackColor="White" BorderColor="#999999" Height="195px" Width="450px" runat="server" BorderStyle="None"
                        OnCancelCommand="DataList_CancelCommand" OnDeleteCommand="DataList_DeleteCommand" OnUpdateCommand="DataList_UpdateCommand"
                        GridLines="Vertical">
                        <SelectedItemStyle Font-Bold="True" ForeColor="White" BackColor="#008A8C"></SelectedItemStyle>
                        <HeaderTemplate>
                              Items
                        </HeaderTemplate>
                        <EditItemStyle BackColor="LightGreen"></EditItemStyle>
                        <AlternatingItemStyle BackColor="Gainsboro"></AlternatingItemStyle>
                        <SeparatorStyle BorderStyle="Groove" BorderColor="#FFE0C0" BackColor="#FFC080"></SeparatorStyle>
                        <ItemStyle ForeColor="Black" BackColor="#EEEEEE"></ItemStyle>
                        <FooterStyle ForeColor="Black" BackColor="#CCCCCC"></FooterStyle>
                        <ItemTemplate>
                              <TABLE style="WIDTH: 476px; HEIGHT: 27px" cellSpacing="1" cellPadding="1" width="476" align="left"
                                    bgColor="#F6A64E" border="0">
                                    <TR>
                                          <TD width="15">
                                                <asp:ImageButton id="imgBtnEdit" runat="server" BorderStyle="None" Width="14px" Height="17px" BackColor="Transparent"
                                                      AlternateText="Edit" ImageAlign="Middle" ImageUrl="images/edit.jpg" CommandName="edit" ToolTip="Edit"></asp:ImageButton>
                                          </TD>
                                          <TD width="50">
                                                Ref:&nbsp;
                                          </TD>
                                          <TD width="120">
                                                <%#DataBinder.Eval(Container.DataItem, "ref")%>
                                          </TD>
                                          <TD width="50">
                                                Item:&nbsp;
                                          </TD>
                                          <TD width="80">
                                                <%# DataBinder.Eval(Container.DataItem, "Item") %>
                                          </TD>
                                          <TD width="65">
                                                Price:&nbsp;
                                          </TD>
                                          <TD width="80">
                                                <%# DataBinder.Eval(Container.DataItem, "Price") %>
                                          </TD>
                                    </TR>
                              </TABLE>
                        </ItemTemplate>
                        <HeaderStyle Font-Bold="True" ForeColor="White" BackColor="#000084"></HeaderStyle>
                        <EditItemTemplate>
                              <TABLE style="WIDTH: 477px; HEIGHT: 35px" cellSpacing="2" cellPadding="2" width="477" align="left"
                                    bgColor="#ffffcc" border="0">
                                    <TR vAlign="center">
                                          <TD width="20">
                                                <asp:ImageButton id="imgBtnCancel" runat="server" AlternateText="Cancel" ImageUrl="images/reset.jpg"
                                                      CommandName="cancel" ToolTip="Cancel"></asp:ImageButton>
                                          </TD>
                                          <TD width="15">
                                                <asp:ImageButton id="imgBtnUpdate" runat="server" AlternateText="Update" ImageUrl="images/save.jpg"
                                                      CommandName="update" ToolTip="Update"></asp:ImageButton>
                                          </TD>
                                          <TD width="15">
                                                <asp:ImageButton id="imgBtnDelete" runat="server" AlternateText="Delete" ImageUrl="images/delete.jpg"
                                                      CommandName="delete" ToolTip="Delete"></asp:ImageButton>
                                          </TD>
                                          <TD width="150">
                                                Ref:
                                                <asp:Label id="Label1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "ref")%>'>
                                                </asp:Label>
                                          </TD>
                                          <TD width="150">
                                                Item:
                                                <asp:TextBox id="Text1" runat="server" BorderStyle="Groove" Width="80px" Height="20px" Text='<%#DataBinder.Eval(Container.DataItem, "Item")%>'>
                                                </asp:TextBox>
                                          </TD>
                                          <TD width="150">
                                                Price:
                                                <asp:TextBox id="Text2" runat="server" BorderStyle="Groove" Width="80px" Height="20px" Text='<%# DataBinder.Eval(Container.DataItem, "Price") %>'>
                                                </asp:TextBox>
                                          </TD>
                                    </TR>
                              </TABLE>
                        </EditItemTemplate>
                  </asp:datalist>
            </form>
      </body>
</HTML>

default.aspx.vb
-------------------
Option Explicit On
Option Strict On
Imports System.Data
Imports System.Data.SqlClient

Public Class Cdefault
    Inherits System.Web.UI.Page
    Dim Cart As DataTable
    Protected WithEvents txtItem As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtQty As System.Web.UI.WebControls.TextBox
    Protected WithEvents txtPrice As System.Web.UI.WebControls.TextBox
    Protected WithEvents btnInsert As System.Web.UI.WebControls.Button
    Protected WithEvents DataList1 As System.Web.UI.WebControls.DataList
    Protected WithEvents txtRef As System.Web.UI.WebControls.TextBox
    Dim CartView As DataView
#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            BindList()
        End If
    End Sub
   
    Sub BindList()
        Dim conP As SqlConnection
        Dim cmdP As SqlCommand
        Dim dtrP As SqlDataReader
        Dim strSQL As String

        conP = New SqlConnection("Server=HHLEE\HHLEE;uid=sa;pwd=;database=master")
        strSQL = "Select * from tblTesting"
        cmdP = New SqlCommand(strSQL, conP)
        conP.Open()
        dtrP = cmdP.ExecuteReader(CommandBehavior.CloseConnection)

        DataList1.DataSource = dtrP
        DataList1.DataBind()
    End Sub 'BindList

    Sub DataList_EditCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs)
        DataList1.EditItemIndex = CInt(e.Item.ItemIndex)
        BindList()
    End Sub 'DataList_EditCommand

    Sub DataList_CancelCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs)
        DataList1.EditItemIndex = -1
        BindList()
    End Sub 'DataList_CancelCommand

    Sub DataList_DeleteCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs)
        Dim item As String = CType(e.Item.FindControl("Label1"), Label).Text
        Dim conP As SqlConnection
        Dim cmdP As SqlCommand
        Dim strSQL As String

        'delete item
        conP = New SqlConnection("Server=HHLEE\HHLEE;uid=sa;pwd=;database=master")
        strSQL = "Delete tblTesting where ref=@ref"
        cmdP = New SqlCommand(strSQL, conP)
        cmdP.Parameters.Add("@ref", CType(item, Integer))

        conP.Open()
        cmdP.ExecuteNonQuery()

        DataList1.EditItemIndex = -1
        BindList()
    End Sub 'DataList_DeleteCommand

    Sub DataList_UpdateCommand(ByVal sender As Object, ByVal e As DataListCommandEventArgs)
        Dim ref As String = CType(e.Item.FindControl("Label1"), Label).Text
        Dim item As String = CType(e.Item.FindControl("Text1"), TextBox).Text
        Dim price As String = CType(e.Item.FindControl("Text2"), TextBox).Text
        Dim conP As SqlConnection
        Dim cmdP As SqlCommand
        Dim strSQL As String

        conP = New SqlConnection("Server=HHLEE\HHLEE;uid=sa;pwd=;database=master")
        strSQL = "Update tblTesting set Item=@Item,Price=@Price where ref=@ref"
        cmdP = New SqlCommand(strSQL, conP)
        cmdP.Parameters.Add("@Item", item)
        cmdP.Parameters.Add("@Price", price)
        cmdP.Parameters.Add("@ref", ref)

        conP.Open()
        cmdP.ExecuteNonQuery()

        DataList1.EditItemIndex = -1
        BindList()
    End Sub 'DataList_UpdateCommand

    Private Sub btnInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnInsert.Click
        CartView.RowFilter = ""
        ' Add new entry.
        Dim conP As SqlConnection
        Dim cmdP As SqlCommand
        Dim strSQL As String

        'add to db
        conP = New SqlConnection("Server=HHLEE\HHLEE;uid=sa;pwd=;database=master")
        strSQL = "Insert into tblTesting(ref,Item,Price) values(@ref,@Item,@Price)"
        cmdP = New SqlCommand(strSQL, conP)
        cmdP.Parameters.Add("@ref", CType(txtRef.Text, Integer))
        cmdP.Parameters.Add("@Item", txtItem.Text)
        cmdP.Parameters.Add("@Price", txtPrice.Text)

        conP.Open()
        cmdP.ExecuteNonQuery()
        DataList1.EditItemIndex = -1
        BindList()
    End Sub

End Class


Regards
x_com
0
manceAuthor Commented:
Hi X_Com,

Sorry for the slow response ... been out of town.

I think you're right regarding inserting data to a datagrid. You could probably do other things to get around it, such as inserting an empty row into the database and using it as the datasource, but it would probably be just as much work.

Thanks for the help.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.