问题描述
我需要将GridView数据复制到Datatable。
我的代码在下面: -
.aspx: -
Hi,
I have a requirement to copy GridView data to Datatable.
My code is below:--
.aspx:--
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns ="false" >
<Columns>
<asp:TemplateField HeaderText="Book Name">
<ItemTemplate>
<%#Eval("BookName")%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<%#Eval("Bookprice")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
.aspx.cs:---
.aspx.cs:---
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataTable dt1 = new DataTable();
dt1.Columns.AddRange(new DataColumn[2] { new DataColumn("BookName"), new DataColumn("BookPrice") });
dt1.Rows.Add("khan Hammond", "10.00");
dt1.Rows.Add("Mojibar", "20.50");
dt1.Rows.Add("Saean Mathews", "11.25");
dt1.Rows.Add("Robin Schidner", "20.35");
Session["QtyTable"] = dt1;
GridView1.DataSource = dt1;
GridView1.DataBind();
}
}
private void getGridInfo()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data .DataColumn(BookName,typeof(String)));
dt.Columns.Add(new System.Data.DataColumn(BookPrice,typeof(String)));
for(int i = 0; i< GridView1.Rows.Count; i ++)
{
dr [i] = GridView1.Rows [0] .Cells [0] .Text;
dr [i + 1] = GridView1.Rows [i] .Cells [i] .Text;
dt.Rows.Add (博士);
}
}
现在当我看到数据表时,它的空白。 />
请发布合适的代码...
谢谢...
private void getGridInfo()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new System.Data.DataColumn("BookName", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("BookPrice", typeof(String)));
for (int i = 0; i < GridView1.Rows.Count; i++)
{
dr[i] = GridView1.Rows[0].Cells[0].Text;
dr[i + 1] = GridView1.Rows[i].Cells[i].Text;
dt.Rows.Add(dr);
}
}
Now when I see the datatable,its blank.
Please post suitable code...
Thanks...
推荐答案
private void getGridInfo()
{
DataTable dt = (DataTable)GridView1.DataSource;
}
private void getGridInfo()
{
DataTable dt = new DataTable();
dt.Columns.Add(new System.Data.DataColumn("BookName", typeof(String)));
dt.Columns.Add(new System.Data.DataColumn("BookPrice", typeof(String)));
for (int i = 0; i < GridView1.Rows.Count; i++)
{
DataRow dr = dt.NewRow();
var row = GridView1.Rows[i];
dr[0] = (row.Cells[0].Controls[0] as DataBoundLiteralControl).Text;
dr[1] = (row.Cells[1].Controls[0] as DataBoundLiteralControl).Text;
dt.Rows.Add(dr);
}
}
这篇关于将Gridview数据重新转换为数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!