Solved

asp.net display datalist containing empty record for new Insert

Posted on 2003-11-11
6
1,664 Views
Last Modified: 2007-12-19
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!
0
Comment
Question by:mance
  • 3
  • 3
6 Comments
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 9727652
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
 

Author Comment

by:mance
ID: 9728155
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
 
LVL 29

Accepted Solution

by:
David H.H.Lee earned 125 total points
ID: 9730696
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:mance
ID: 9731420
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
 
LVL 29

Expert Comment

by:David H.H.Lee
ID: 9745099
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
 

Author Comment

by:mance
ID: 9806880
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

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Hello, all! I just recently started using Microsoft's IIS 7.5 within Windows 7, as I just downloaded and installed the 90 day trial of Windows 7. (Got to love Microsoft for allowing 90 days) The main reason for downloading and testing Windows 7 is t…
This demonstration started out as a follow up to some recently posted questions on the subject of logging in: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_28634665.html and http://www.experts-exchange.com/Programming/…
This video discusses moving either the default database or any database to a new volume.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now