You must Sign In to post a response.
  • Category: ASP.NET

    copy gridview data to dataTable

    hi how to bind a Datatable with gridview....i hv gridview populated nd want
    all the rows of grid to be copied in datatable...how to do this
  • #345818
    If your grid view has data in it, you can get the data by using below statements


    DataTable dtGridView = (DataTable)GridView1.DataSource;


    HTH

    Regards,
    Satish

  • #345821
    hi,

    check this example

    in design view:

    <asp:GridView ID="gdview" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID" >
    <Columns>
    <asp:BoundField HeaderText="Category Name" DataField="CategoryName" SortExpression="CategoryName" />
    <asp:CommandField ShowEditButton="True" />
    <asp:TemplateField>
    <ItemTemplate>
    <asp:LinkButton ID="lnkdel" runat="server" Text="Delete" CommandName="Delete"></asp:LinkButton>

    </ItemTemplate>

    </asp:TemplateField>
    </Columns>
    </asp:GridView>
    <asp:Button ID="btnsubmit" runat="server" Text="Copy Data" OnClick="btnsubmit_Click" />

    in code behind:
    protected void Page_Load(object sender, EventArgs e)
    {

    if (!Page.IsPostBack)
    {
    bindgrid();
    }

    }

    public void bindgrid()
    {
    SqlConnection conn = new SqlConnection("Data Source='localhost';Initial Catalog='Northwind';Integrated Security=SSPI;Persist Security Info=False ");
    SqlDataAdapter da = new SqlDataAdapter("", conn);
    da.SelectCommand = new SqlCommand("select CategoryName,CategoryID from Categories", conn);
    DataSet ds = new DataSet();
    da.Fill(ds, "data");
    gdview.DataSource = ds.Tables[0].DefaultView;
    gdview.DataBind();


    }

    protected void btnsubmit_Click(object sender, EventArgs e)
    {
    DataTable dtable = new DataTable();
    dtable.Columns.Add("categoryname");
    for (int i = 0; i <= gdview.Rows.Count - 1; i++)
    {
    DataRow drow = dtable.NewRow();
    drow[0] = gdview.Rows[i].Cells[0].Text;
    dtable.Rows.Add(drow);
    }

    }

    Regards,
    Phani Harshitha Madala
    My blog:www.phmadala.wordpress.com

    Rate this Response[Excellent/Good/Poor]


  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.