2

I'm working on my SQL project,I have created a gridview in which I bound the values in gridview footer according to table columns.

Basically, I'm creating a gridview in which user insert values and create a table. But, I'm facing a problem when the table contains 'One' record or more than one record then it's working fine, but I want that when table empty then footer of gridview show which contains "textboxes", "checkboxes" and "dropdownlist".

When table contains one record then this gridview show, it's working fine, here is

image

When table contains no data then this gridview show

image

How can I show this type of gridview

image

when the table has no data so that user insert values and create table?

Here is my ASPX markup:

 <asp:GridView ID="GridView1" runat="server" ShowHeaderWhenEmpty="True" 
    AutoGenerateColumns="False" BackColor="#DEBA84"
    BorderColor="#DEBA84"  BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
     ShowFooter="True" Style="margin-left: 136px; margin-top: 72px;
    margin-right: 0px;" Height="16px" Width="685px" 
     DataSourceID="sql">
    <Columns>
        <asp:TemplateField HeaderText="Column_Name" SortExpression="Column_Name">
            <EditItemTemplate>
                 <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Column_Name") %>'></asp:TextBox>
                <asp:RequiredFieldValidator Text="*" ID="colname" ControlToValidate="txtName"
                    runat="server" ErrorMessage="Column Name is Required" ForeColor="Red">
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("Column_Name") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:TextBox ID="txtColName" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ValidationGroup="INSERT" Text="*" ID="insertcolname" ControlToValidate="txtColName"
                    runat="server" ErrorMessage="Column Name is Required" ForeColor="Red">
                </asp:RequiredFieldValidator>
           </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Data_Type" SortExpression="Data_Type">
            <EditItemTemplate>
                <asp:DropDownList ID="DropDownList1" runat="server" SelectedValue='<%# Bind("Data_Type") %>'>
                    <asp:ListItem>Select Datatype</asp:ListItem>
                    <asp:ListItem>int</asp:ListItem>
                    <asp:ListItem>Float</asp:ListItem>
                    <asp:ListItem>Varchar(50)</asp:ListItem>
                    <asp:ListItem>Varchar(100)</asp:ListItem>
                    <asp:ListItem>double</asp:ListItem>
                </asp:DropDownList>
                <asp:RequiredFieldValidator ID="datatype" ControlToValidate="DropDownList1"
                    runat="server" ErrorMessage="Data Type is Required" ForeColor="Red" InitialValue="Select Datatype">
                </asp:RequiredFieldValidator>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("Data_Type") %>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
                <asp:DropDownList ID="DropDownList2" runat="server">
                    <asp:ListItem>Select Datatype</asp:ListItem>
                    <asp:ListItem>int</asp:ListItem>
                    <asp:ListItem>Float</asp:ListItem>
                    <asp:ListItem>Varchar(50)</asp:ListItem>
                    <asp:ListItem>Varchar(100)</asp:ListItem>
                    <asp:ListItem>double</asp:ListItem>
                </asp:DropDownList>
                <asp:RequiredFieldValidator ValidationGroup="INSERT" Text="*"  ID="datatype" ControlToValidate="DropDownList2"
                    runat="server" ErrorMessage="Data Type is Required" ForeColor="Red" InitialValue="Select Datatype">
                </asp:RequiredFieldValidator>
            </FooterTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Allow_Null_" SortExpression="Allow_Null_">
                                <EditItemTemplate>
                                    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%#Convert.ToBoolean(DataBinder.Eval(Container.DataItem,"Allow_Null_")) %>'/>
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem,"Allow_Null_"))%>' enabled="false" />
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:CheckBox ID="nulll" runat="server" />
                                </FooterTemplate>
                            </asp:TemplateField>
                            <asp:TemplateField HeaderText="Primary_Key_" SortExpression="Primary_Key_">
                                <EditItemTemplate>
                                    <asp:CheckBox ID="CheckBox2" runat="server" Checked='<%# Convert.ToBoolean(DataBinder.Eval(Container.DataItem,"Primary_Key_")) %>' />
                                </EditItemTemplate>
                                <ItemTemplate>
                                    <asp:CheckBox ID="CheckBox2" runat="server" 
                                        Checked='<%#Convert.ToBoolean(DataBinder.Eval(Container.DataItem,"Primary_Key_")) %>' Enabled="false" />
                                </ItemTemplate>
                                <FooterTemplate>
                                    <asp:CheckBox ID="primary" runat="server" />
                                </FooterTemplate>
                            </asp:TemplateField>

        <asp:CommandField ShowEditButton="True" />
        <asp:CommandField ShowDeleteButton="True" />

        <asp:TemplateField HeaderText="Insert">
        <FooterTemplate>


             <asp:LinkButton ValidationGroup="INSERT" ID="LinkButton1" runat="server" OnClick="lbinssert">INSERT</asp:LinkButton>
            </FooterTemplate>
        </asp:TemplateField>


    </Columns>
    <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
    <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
    <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
    <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
    <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
    <SortedAscendingCellStyle BackColor="#FFF1D4" />
    <SortedAscendingHeaderStyle BackColor="#B95C30" />
    <SortedDescendingCellStyle BackColor="#F1E5CE" />
    <SortedDescendingHeaderStyle BackColor="#93451F" />
      </asp:GridView>

<asp:ValidationSummary ValidationGroup="INSERT" ID="ValidationSummary1" ForeColor="Red"
    runat="server" Height="25px" style="margin-left: 140px" />
    <br />
<input type="submit" style="position:relative; width:30px; left:452px; top: 0px; width: 86px;" 
     value="Create table" name="create"/>
<asp:ValidationSummary ID="ValidationSummary2" ForeColor="Red" runat="server" 
    style="margin-left: 142px" />
    <asp:SqlDataSource ID="sql" runat="server" 
     ConnectionString="<%$ ConnectionStrings:db_compilerConnectionString %>" 

     SelectCommand="SELECT [Column_Name], [Data_Type], [Allow_Null_], [Primary_Key_], [Date] FROM [tbl_field]"
     DeleteCommand="DELETE  FROM [tbl_field] WHERE [Field_id]=@field" InsertCommand="INSERT INTO [tbl_field] ([Column_Name],[Data_Type],[Database_id],[Allow_Null_],[Primary_Key_])Values (@ColumnName,@Dtype,@id,@null,@primary)"
     UpdateCommand="UPDATE [tbl_field] SET [Column_Name]=@ColumnName,[Data_Type]=@Dtype,[Database_id]=@id,[Allow_Null_]=@null,[Primary_Key_]=@primary">
     <DeleteParameters>
     <asp:Parameter Name="field" Type="Int32" />
     </DeleteParameters>
     <InsertParameters>
     <asp:Parameter Name="ColumnName" Type="String" />
      <asp:Parameter Name="Dtype" Type="String" />
       <asp:Parameter Name="id" Type="String" />
        <asp:Parameter Name="null" Type="Boolean" />
         <asp:Parameter Name="primary" Type="Boolean" />


     </InsertParameters>
     <UpdateParameters>
      <asp:Parameter Name="ColumnName" Type="String" />
      <asp:Parameter Name="Dtype" Type="String" />
       <asp:Parameter Name="id" Type="String" />
        <asp:Parameter Name="null" Type="Boolean"/>
         <asp:Parameter Name="primary" Type="Boolean" />

     </UpdateParameters>

 </asp:SqlDataSource>

Here is my aspx.cs code:

public void lbinssert(Object sender,EventArgs e)
{
    sql.InsertParameters["ColumnName"].DefaultValue =
        ((TextBox)GridView1.FooterRow.FindControl("txtColName")).Text;
    sql.InsertParameters["Dtype"].DefaultValue =
        ((DropDownList)GridView1.FooterRow.FindControl("DropDownList2")).Text;
    sql.InsertParameters["id"].DefaultValue =
       ((DropDownList)GridView1.FooterRow.FindControl("DropDownList2")).Text;
    sql.InsertParameters["null"].DefaultValue =
      ((CheckBox)GridView1.FooterRow.FindControl("nulll")).Checked == true ? "true" : "false";
    sql.InsertParameters["primary"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("primary")).Checked == true ? "true" : "false";

    sql.Insert();
   }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Saira
  • 123
  • 3
  • 18

2 Answers2

0

I would suggest the following solution:

Taking into account that the datatable you return will contain zero records by testing it dataTable.Rows.Count == 0.

When the above dataTable returns zero records then run the piece of code below:

if(dataTable.Rows.Count == 0)
{
  FixGridFooter(dataTable);
}
else
{
   GridView1.DataSource = datatable;
   GridView1.DataBind();
}

The method adds a dummy record to a datatable and then bound to the Gridview and displayed in the footer.

private void FixGridFooter(DataTable dataSource)
{
    //add blank row to the the resultset
    dataSource.Rows.Add(dataSource.NewRow());
    dataSource.Rows[0]["Value1"] = 0;
    dataSource.Rows[0]["Value2"] = "";
    dataSource.Rows[0]["RecordDate"] = DateTime.Now.ToString("dd MMM yyyy");
    dataSource.Rows[0]["Checked"] = false;
    GridView1.DataSource = dataSource;
    GridView1.DataBind();

    //hide empty row - if you want to display it on an event like a button click else it will display as per default.
    GridView1.Rows[0].Visible = false;
 }

The insert of new records will then happen via the FooterTemplate inside the <asp:TemplateField>.

When you have anevent or in the load event you can call GridView1.ShowFooter = true;. When the datatable eventually returns records then the ShowFooter can be set to invisible again.

This is a very quick and dirty solution. Obviously a lot of optimizations can be made but I'll leave than to you.

In the footer tamplte will be a button Insert with a CommandName="Insert". In the RowCommand event you will test for the command name and then retrieve value from the rows for insert

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (e.CommandName.Equals("Insert")
                {
                    //insert code
                    var returnString = GridView1.FooterRow.FindControl("txtValue") as TextBox;
                    GridView1.ShowFooter = false;
                }
}

Update and Delete you can add via standard GridView settings in the designer properties and add functionality accordingly.

Conrad Lotz
  • 8,200
  • 3
  • 23
  • 27
  • But I want to insert values using footer of the gridview ,but you provided me solution which contains fields added into gridview but i want insert,edit,delete data into girdview by data bind table – Saira Apr 11 '16 at 13:22
  • You right but problem is every time table is not empty.My Table contains "userid" and every user can crate table when page load then table contains data and this method is not cal when table contains data,i want when user create new table then this gridview show ,user can create table, – Saira Apr 11 '16 at 13:34
  • I want that when user click on "create table button" then every time this gridview ,so user can insert values and create table,but you provide me solution in which when table is empty first time then this gridview open otherwise it will not – Saira Apr 11 '16 at 13:44
  • So the Create Table button will call GridView1.ShowFooter = true and then the Insert button will be available to execute once all the values are completed and validation passed. – Conrad Lotz Apr 11 '16 at 15:12
0

You have to insert dummy row when Gridview is empty .

here are the useful links .

https://aspdotnetcodehelp.wordpress.com/2015/03/24/how-to-show-header-and-footer-when-gridview-is-empty-in-asp-net/

and

Show gridview footer on empty grid?

Community
  • 1
  • 1
KanisXXX
  • 757
  • 7
  • 19