4 Replies - 11025 Views - Last Post: 18 October 2011 - 05:17 AM Rate Topic: -----

#1 rizwanit  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 11-October 11

How to populate data from database to item template in Gridview

Posted 11 October 2011 - 12:28 AM

Mygridview itemtemplate



<table>
<tr>
<td>
<asp:GridView ID="GridView1" runat="server" Font-Bold="True" ForeColor="#BF6000"
Height="191px" Width="600px" AutoGenerateColumns="False"
BorderStyle="None" BorderWidth="1px"
HorizontalAlign="Justify" onselectedIndexChanged="GridView1_SelectedIndexChanged1"
OnRowDataBound="GridView1_RowDataBound"
onrowcommand="GridView1_RowCommand">
<HeaderStyle BackColor="#FFFFC4" Font-Bold="True" ForeColor="#BF6000" />
<Columns>
<asp:TemplateField HeaderText="S.No">
<ItemTemplate>
<asp:Label ID="label10" runat="server" Font-Bold="true" ForeColor="#BF6000" Text="<%# Container.DataItemIndex + 1 %>">
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Serv Code" >
<ItemTemplate>
<asp:TextBox ID="TxtServiceCode" Font-Bold="true" ForeColor="#BF6000" Text='<%# Bind("ServiceCode") %>'
runat="server" Width="55px">
</asp:TextBox>

<asp:Button ID="btninsert" runat="server" BackColor="Ivory" Font-Bold="true" ForeColor="#BF6000" text="Insert" CommandName="Insert" UseSubmitbehavior="false" />

</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox ID="TxtServiceName" runat="server" ReadOnly="true" Font-Bold="true" ForeColor="#BF6000" Width="150px" Text='<%# DataBinder.Eval(Container, "DataItem.ServiceName") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Serv Amt">
<ItemTemplate>
<asp:TextBox ID="TxtServiceAmount" ReadOnly="true" Font-Bold="true" ForeColor="#BF6000" Text='<%# DataBinder.Eval(Container,"DataItem.ServiceAmount") %>'
runat="server" Width="55px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Qty">
<ItemTemplate>
<asp:TextBox ID="Txtquantity" Font-Bold="true" ForeColor="#BF6000" Text='<%# DataBinder.Eval(Container,"DataItem.Quantity") %>'
runat="server" Width="55px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Disc Amt">
<ItemTemplate>
<asp:TextBox ID="TxtdiscAmt" Font-Bold="true" ForeColor="#BF6000" Text='<%# DataBinder.Eval(Container,"DataItem.Discount") %>'
runat="server" Width="55px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Net Amt">
<ItemTemplate>
<asp:TextBox ID="TxtNetAmt" ReadOnly="true" Font-Bold="true" ForeColor="#BF6000" Text='<%# DataBinder.Eval(Container,"DataItem.NetAmountPaid") %>'
runat="server" Width="55px"></asp:TextBox>

</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>


I want to display data through a stored procedure my code is:

//DataSet dss = new DataSet();
//SqlConnection MyConnection = new SqlConnection("server=prog;database=mydatabase;UID=sa;PWD=123;");
//SqlDataAdapter mydataadapter = new SqlDataAdapter("GetServCodes", MyConnection);
//mydataadapter.SelectCommand.CommandType = CommandType.StoredProcedure;
//mydataadapter.SelectCommand.Parameters.Add(new SqlParameter("ServiceCode", SqlDbType.VarChar, 10));
//mydataadapter.SelectCommand.Parameters["@ServiceCode"].Value = dss.Tables[1].Rows[1].ToString();
//mydataadapter.Fill(ds, "ServiceCode");
//TxtserviceCode.Text = ds.Tables[0].Rows[rno]["ServiceCode"].ToString();
//mydataadapter.Dispose();
//MyConnection.Close();

After the data is displayed i want to perform calculations like:

s.no s.name seramount quantity discount netamount




i don't where is my code wrong help me to solve the problem.!!!!!!!!!!!!

Is This A Good Question/Topic? 1
  • +

Replies To: How to populate data from database to item template in Gridview

#2 Theomi  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 9
  • View blog
  • Posts: 88
  • Joined: 17-January 10

Re: How to populate data from database to item template in Gridview

Posted 11 October 2011 - 02:11 AM

Please use code tags when posting code...
Makes it a lot easier to help you
Was This Post Helpful? 0
  • +
  • -

#3 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 446
  • View blog
  • Posts: 1,501
  • Joined: 28-April 09

Re: How to populate data from database to item template in Gridview

Posted 11 October 2011 - 09:05 AM

what calculations are you wanting to perform? It looks to me like you just listed column names. Are those the names of columns that are coming back from the stored procedure? What is the exact problem you are having? Are you getting any exceptions/errors?
Was This Post Helpful? 0
  • +
  • -

#4 rizwanit  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 13
  • Joined: 11-October 11

Re: How to populate data from database to item template in Gridview

Posted 16 October 2011 - 11:08 PM

View PostNakor, on 11 October 2011 - 09:05 AM, said:

what calculations are you wanting to perform? It looks to me like you just listed column names. Are those the names of columns that are coming back from the stored procedure? What is the exact problem you are having? Are you getting any exceptions/errors?


Thanks for the Reply Nakor,
my scenario is,i am having a grid,in that i had added textboxes through itemtemplate,from database i want to display data to the gridview textboxes,is this code correct,i would appreciate if you share your knowledge with me............
Was This Post Helpful? 0
  • +
  • -

#5 hemantwithu  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 5
  • View blog
  • Posts: 31
  • Joined: 18-October 11

Re: How to populate data from database to item template in Gridview

Posted 18 October 2011 - 05:17 AM

Hi this is a Sample Example done by me
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InplaceInGridView.aspx.cs"
    Inherits="InplaceInGridView" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Inplace Edit in GridView</title>
    <script language="javascript" type="text/javascript">
        function textonfocus(textBox) {
            textBox.className = 'loginHighlight';
        }
        function textonblur(textBox) {
            textBox.className = 'loginNormal';
        }  
    </script>
    <style type="text/css">
        .loginHighlight
        {
            border: 2px solid grey;
            background: #FFFFFF url(     "~/Images/gr.png" ) repeat-x 0 1px;
            color: #666666;
            width: 80%;
        }
        .loginNormal
        {
            border: 1px solid #cdcdcd;
            background: #FFFFFF url(       "~/Images/gr.png" ) repeat-x 0 1px;
            color: #666666;
            width: 80%;
            opacity: 0.6;
            filter: alpha(opacity=60);
        }
        .frmLbl
        {
            font-family: serif;
        }
        .btnNormal
        {
            border: 1px solid #cdcdcd;
            background: #FFFFFF url(       "~/Images/grG.png" ) repeat-x 0 1px;
            color: black;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <center>
        <div>
            <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
                ForeColor="#333333" GridLines="Both" Width="60%" OnRowEditing="GridView1_RowEditing"
                AllowPaging="true" PageSize="3" OnPageIndexChanging="GridView1_PageIndexChanging"
                OnRowDataBound="GridView1_RowDataBound" DataKeyNames="UserID">
                <RowStyle BackColor="#EFF3FB" />
                <Columns>
                    <asp:TemplateField>
                        <HeaderTemplate>
                            <table width="100%" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td style="width: 15%;" align="left">
                                        First Name
                                    </td>
                                    <td style="width: 15%;" align="left">
                                        Last Name
                                    </td>
                                    <td style="width: 35%;" align="left">
                                        Web
                                    </td>
                                    <td style="width: 35%;" align="left">
                                        Email
                                    </td>
                                </tr>
                            </table>
                        </HeaderTemplate>
                        <ItemTemplate>
                            <table width="100%" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td style="width: 15%;" align="left">
                                        <%#DataBinder.Eval(Container.DataItem, "FirstName")%>
                                    </td>
                                    <td style="width: 15%;" align="left">
                                        <%#DataBinder.Eval(Container.DataItem, "LastName")%>
                                    </td>
                                    <td style="width: 35%;" align="left">
                                        <%#DataBinder.Eval(Container.DataItem, "Web")%>
                                    </td>
                                    <td style="width: 35%;" align="left">
                                        <%#DataBinder.Eval(Container.DataItem, "Email")%>
                                    </td>
                                </tr>
                            </table>
                        </ItemTemplate>
                        <EditItemTemplate>
                            <center>
                                <asp:RoundedCornersExtender ID="rce" runat="server" TargetControlID="pnlHead" Radius="6"
                                    Corners="Top" BorderColor="black">
                                </asp:RoundedCornersExtender>
                                <asp:Panel ID="pnlHead" runat="server" Font-Bold="true" ForeColor="white" BackColor="#507CD1"
                                    Width="50%">
                                    <center>
                                        <table>
                                            <tr>
                                                <td>
                                                    Updating
                                                    <%#DataBinder.Eval(Container.DataItem, "FirstName")%>,
                                                    <%#DataBinder.Eval(Container.DataItem, "LastName")%>
                                                </td>
                                            </tr>
                                        </table>
                                    </center>
                                </asp:Panel>
                                <asp:RoundedCornersExtender ID="rceDetail" runat="server" TargetControlID="pnlDetail"
                                    Radius="6" Corners="Bottom" BorderColor="black">
                                </asp:RoundedCornersExtender>
                                <asp:Panel ID="pnlDetail" runat="server" Width="50%">
                                    <table width="100%">
                                        <tr>
                                            <td align="right" style="width: 30%">
                                                First Name:
                                            </td>
                                            <td style="padding-right: 10px;">
                                                <asp:TextBox ID="tbFirstName" Width="100%" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "FirstName")%>'></asp:TextBox>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                Last Name:
                                            </td>
                                            <td style="padding-right: 10px;">
                                                <asp:TextBox ID="tbLastName" runat="server" Width="100%" Text='<%#DataBinder.Eval(Container.DataItem, "LastName")%>'></asp:TextBox>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                Web:
                                            </td>
                                            <td style="padding-right: 10px;">
                                                <asp:TextBox ID="tbWeb" runat="server" Width="100%" Text='<%#DataBinder.Eval(Container.DataItem, "Web")%>'></asp:TextBox>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="right">
                                                eMail:
                                            </td>
                                            <td style="padding-right: 10px;">
                                                <asp:TextBox ID="tbEmail" runat="server" Width="100%" Text='<%#DataBinder.Eval(Container.DataItem, "eMail")%>'></asp:TextBox>
                                            </td>
                                        </tr>
                                    </table>
                                    <div style="padding-top: 3px; border-top: thin solid black;" id="divUpdate">
                                        <asp:Button CssClass="btnNormal" runat="server" ID="bUpdate" Text="Update" onclick="bUpdate_Click" />&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button
                                            onclick="bCancel_Click" CssClass="btnNormal" runat="server" ID="bCancel" Text="Cancel" />
                                    </div>
                                </asp:Panel>
                            </center>
                        </EditItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ShowEditButton="true" ButtonType="Image" EditImageUrl="~/images/edit.gif"
                        HeaderText="Edit" ShowCancelButton="false" UpdateImageUrl="~/images/Blank.gif"
                        ItemStyle-Width="20" />
                </Columns>
                <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <AlternatingRowStyle BackColor="White" />
            </asp:GridView>
        </div>
    </center>
    </form>
</body>
</html>




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class InplaceInGridView : System.Web.UI.Page
{
    private int iCurrentEdit = -1;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView1.DataSource = CreateTable();
            GridView1.DataBind();
        }
        else
        {
            if (ViewState["editRowIndex"] != null) // indicates we have values from edit which needs to be saved in viewstate
            {
                int iEditRowID = int.Parse((ViewState["editRowIndex"] == null ? "-2" : ViewState["editRowIndex"].ToString())); // get current edit row index

                // get all elements from edit template
                TextBox tbF = (TextBox)GridView1.Rows[iEditRowID].FindControl("tbFirstName");
                TextBox tbL = (TextBox)GridView1.Rows[iEditRowID].FindControl("tbLastName");
                TextBox tbW = (TextBox)GridView1.Rows[iEditRowID].FindControl("tbWeb");
                TextBox tbE = (TextBox)GridView1.Rows[iEditRowID].FindControl("tbEmail");

                // save all values into viewstate for future use
                if (tbF != null)
                {
                    ViewState.Add("fname", tbF.Text);
                    ViewState.Add("lname", tbL.Text);
                    ViewState.Add("web", tbW.Text);
                    ViewState.Add("email", tbE.Text);
                }
            }
        }
    }
    private DataTable CreateTable()
    {
        DataTable table = new DataTable();

        DataColumn fName = new DataColumn("FirstName");
        DataColumn lName = new DataColumn("LastName");
        DataColumn email = new DataColumn("eMail");
        DataColumn web = new DataColumn("Web");
        DataColumn userID = new DataColumn("UserID");
        table.Columns.Add(fName);
        table.Columns.Add(lName);
        table.Columns.Add(email);
        table.Columns.Add(web);
        table.Columns.Add(userID);

        DataRow row = null;
        String[,] sData = new string[,] 
            {{"John ","John","johnj@jj.info","http://www.jj.info","1"},
            {"Mothow","Rose","mrose@mr.com","http://www.mrose.com","2"},
            {"Henry","V","hva@hva.com","http://www.hva.com","3"},
            {"Jack","F","fjack@jf.com","http://www.fjack.com","4"}};

        for (int iCtr = 0; iCtr < sData.Length / 5; iCtr++)
        {
            row = table.NewRow();
            row["FirstName"] = sData[iCtr, 0];
            row["LastName"] = sData[iCtr, 1];
            row["eMail"] = sData[iCtr, 2];
            row["Web"] = sData[iCtr, 3];
            row["UserID"] = sData[iCtr, 4];
            table.Rows.Add(row);
        }
        return table;
    }
    protected void GridView1_RowEditing(Object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        GridView1.DataSource = CreateTable();
        GridView1.DataBind();
        ViewState.Add("editRowIndex", e.NewEditIndex);
        ImageButton editButton;

        foreach (GridViewRow row in GridView1.Rows)
        {
            if (row.RowIndex != e.NewEditIndex)
            {
                editButton = (ImageButton)(row.Cells[1].Controls[0]);
                editButton.ImageUrl = "./edit_off.gif";
                editButton.Enabled = false;
            }
            else
            {
                ViewState.Add("EditRowID", row.DataItemIndex.ToString());
                if (ViewState["fname"] != null) // indicates we have values from previous editing session which are not saved
                {
                    // get elements from edit template
                    TextBox tbF = (TextBox)row.FindControl("tbFirstName");
                    TextBox tbL = (TextBox)row.FindControl("tbLastName");
                    TextBox tbW = (TextBox)row.FindControl("tbWeb");
                    TextBox tbE = (TextBox)row.FindControl("tbEmail");

                    // restore previous values
                    tbF.Text = ViewState["fname"].ToString();
                    tbL.Text = ViewState["lname"].ToString();
                    tbW.Text = ViewState["web"].ToString();
                    tbE.Text = ViewState["email"].ToString();
                }
            }
        }
    }

    protected void bUpdate_Click(object sender, EventArgs e)
    {
        // Put data update code here
        TextBox tbF = (TextBox)GridView1.Rows[GridView1.EditIndex].FindControl("tbFirstName");
        TextBox tbL = (TextBox)GridView1.Rows[GridView1.EditIndex].FindControl("tbLastName");
        TextBox tbW = (TextBox)GridView1.Rows[GridView1.EditIndex].FindControl("tbWeb");
        TextBox tbE = (TextBox)GridView1.Rows[GridView1.EditIndex].FindControl("tbEmail");

        // now you have all values entered by user
        // set those values in dataset and update
        // or generate UPDATE sql statement here and save values in db.
        // more details / example can be found at 
        // http://msdn.microsoft.com/en-us/library/ms972948.aspx
        // OR
        // http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx
        object Value = GridView1.EditIndex;
        DataTable dtTemp = new DataTable();
        dtTemp = CreateTable();
        int Id = GridView1.EditIndex + 1;
        foreach (DataRow row in dtTemp.Rows)
        {
            if (Convert.ToInt32(row["USERID"]) == Id)
            {
                row["FirstName"] = tbF.Text;
                row["LastName"] = tbL.Text;
                row["eMail"] = tbE.Text;
                row["Web"] = tbW.Text;
            }
        }
        dtTemp.AcceptChanges();
        refreshData();
    }

    protected void bCancel_Click(object sender, EventArgs e)
    {
        // Put data Cancel code here
        refreshData();
    }

    protected void GridView1_PageIndexChanging(Object objDGName, GridViewPageEventArgs e)
    {

        GridView1.DataSource = CreateTable();
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.EditIndex = -1;
        GridView1.DataBind();

        if (iCurrentEdit != -1)
        {
            GridView1_RowEditing(GridView1, new GridViewEditEventArgs(iCurrentEdit));
        }
    }

    protected void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow ||
            e.Row.RowType == DataControlRowType.EmptyDataRow)
        {
            int iEditRowID = int.Parse((ViewState["EditRowID"] == null ? "-2" : ViewState["EditRowID"].ToString()));
            if (iEditRowID != -2 && e.Row.DataItemIndex == iEditRowID)
            {
                iCurrentEdit = e.Row.RowIndex;

                //TextBox tbF = (TextBox)e.Row.FindControl("tbFirstName");
                //

                //ViewState.Add("fname", tbF.Text); 
                //
            }
            else if (iEditRowID != -2)
            {
                ImageButton editButton;
                editButton = (ImageButton)(e.Row.Cells[1].Controls[0]);
                editButton.ImageUrl = "./edit_off.gif";
                editButton.Enabled = false;
            }
        }
    }

    private void refreshData()
    {
        GridView1.EditIndex = -1;
        ViewState["EditRowID"] = null;
        GridView1.DataSource = CreateTable();
        GridView1.DataBind();

        // clear viewstate
        ViewState["fname"] = null;
        ViewState["lname"] = null;
        ViewState["web"] = null;
        ViewState["email"] = null;
        ViewState["editRowIndex"] = null;
    }
}



Was This Post Helpful? 0
  • +
  • -

Page 1 of 1