关于在内嵌DropDownList的GridView中获取DropDownList选项的问题

masterkill 2009-03-09 12:43:49
前辈们好
如今我在GridView中添加了DropDownList,DropDownList通过
DropDownList1.Items.Add(new ListItem("True"));
DropDownList1.Items.Add(new ListItem("False"));
的方式添加了选项。我想把经过选择后的DropDownList的值写入到Excel中,获取值得代码如下,且没有问题:
for(int i=4;i<=GridView1.Rows.Count+3;i++)
{
DropDownList ddl=(DropDownList)GridView1.Rows[i-4].Cells[2].FindControl("DropDownList1");
myExcel.Cells[i,3]=ddl.SelectedItem.Text;
}

现在的问题是,当我将资料写入到Excel中时,若不进行分页(即不存在重新绑定数据),则可以成功;若要分页,则由于重新绑定了数据,就不能获取到DropDownList的选择值,请前辈帮解决一下关于又可以分页,又可以获取到SelectedItem.Text的问题(以上代码在未分页状况下可以成功)。
...全文
150 16 打赏 收藏 转发到动态 举报
写回复
用AI写文章
16 条回复
切换为时间正序
请发表友善的回复…
发表回复
liuyeede 2009-03-10
  • 打赏
  • 举报
回复
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
PagerSettings-Mode="NumericFirstLast" AllowPaging="True"
OnPageIndexChanging="PageIndexChanging" OnPageIndexChanged="PageIndexChanged">

<Columns>
<asp:BoundField DataField="CompanyName" HeaderText="公司名称" />
<asp:BoundField DataField="ContactName" HeaderText="联系人" />
<asp:BoundField DataField="Phone" HeaderText="联系电话" />
<asp:TemplateField HeaderText="测试DropDownList" ShowHeader= "true">
<ItemTemplate>
<asp:DropDownList ID="TestDDL" runat="server">
<asp:ListItem Value="1" Text="One" />
<asp:ListItem Value="2" Text="Two"/>
<asp:ListItem Value="3" Text="Three" />
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</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;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
public static string sqlStr = "Select CompanyName,ContactName,Phone From Customers";
public static int allRows = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bind();
}
}

private void bind()
{
string connStr = ConfigurationManager.ConnectionStrings["TestSqlConnection"].ConnectionString;

SqlConnection conn = new SqlConnection(connStr);
DataSet dt = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
try
{
conn.Open();
da.Fill(dt, "Customers");
allRows=dt.Tables["Customers"].Rows.Count;
}
catch
{
throw new ApplicationException("数据库错误");
}
finally
{
conn.Close();
}

this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}

int CaculateLastRowIndex()
{
int ps = this.GridView1.PageSize;
int pi = this.GridView1.PageIndex;
return (ps * pi + ps > allRows) ? allRows % ps - 1 : ps - 1;
}

private void CachDropDownListSelectIndex( )
{
string dpl_selectIndexStr =string.Empty;
string cacheKey = "Page" + GridView1.PageIndex.ToString();
for (int i = 0; i <= CaculateLastRowIndex(); i++)
{
dpl_selectIndexStr = dpl_selectIndexStr+((DropDownList)(this.GridView1.Rows[i].FindControl("TestDDL"))).SelectedIndex.ToString();
dpl_selectIndexStr = dpl_selectIndexStr + "|";
}
dpl_selectIndexStr = dpl_selectIndexStr.Substring(0, dpl_selectIndexStr.Length - 1);
Cache[cacheKey] = dpl_selectIndexStr;

}

private void GetCachedDropDownListSelectedIndex( )
{
string cacheKey = "Page" + GridView1.PageIndex.ToString();
if ((Cache[cacheKey] == null)||(Cache[cacheKey].ToString()==string.Empty))
{
return;
}
string dpl_selectIndexStr = Cache[cacheKey].ToString();
string[] selectedIndex = dpl_selectIndexStr.Split('|');

for (int i = 0; i <= CaculateLastRowIndex(); i++)
{
((DropDownList)(this.GridView1.Rows[i].FindControl("TestDDL"))).SelectedIndex = int.Parse(selectedIndex[i]);
Response.Write(((DropDownList)(this.GridView1.Rows[i].FindControl("TestDDL"))).SelectedIndex.ToString());

}

}

protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.CachDropDownListSelectIndex();//换页以前的PageIndex
GridView1.PageIndex = e.NewPageIndex;
bind();

}

protected void PageIndexChanged(object sender, EventArgs e)
{
this.GetCachedDropDownListSelectedIndex(); //换页以后的PageIndex
}
}


liuyeede 2009-03-10
  • 打赏
  • 举报
回复
demo给你做好了:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
public static string sqlStr = "Select CompanyName,ContactName,Phone From Customers";
public static int allRows = 0;
protected void Page_Load(object sender, EventArgs e)
{

if (!IsPostBack)
{
bind();
}

}

private void bind()
{
string connStr = ConfigurationManager.ConnectionStrings["TestSqlConnection"].ConnectionString;

SqlConnection conn = new SqlConnection(connStr);
DataSet dt = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn);
try
{
conn.Open();
da.Fill(dt, "Customers");
allRows=dt.Tables["Customers"].Rows.Count;
}
catch
{
throw new ApplicationException("数据库错误");
}
finally
{
conn.Close();
}

this.GridView1.DataSource = dt;
this.GridView1.DataBind();
}

int CaculateLastRowIndex()
{
int ps = this.GridView1.PageSize;
int pi = this.GridView1.PageIndex;
return (ps * pi + ps > allRows) ? allRows % ps - 1 : ps - 1;
}

private void CachDropDownListSelectIndex( )
{
string dpl_selectIndexStr =string.Empty;
string cacheKey = "Page" + GridView1.PageIndex.ToString();
for (int i = 0; i <= CaculateLastRowIndex(); i++)
{
dpl_selectIndexStr = dpl_selectIndexStr+((DropDownList)(this.GridView1.Rows[i].FindControl("TestDDL"))).SelectedIndex.ToString();
dpl_selectIndexStr = dpl_selectIndexStr + "|";
}
dpl_selectIndexStr = dpl_selectIndexStr.Substring(0, dpl_selectIndexStr.Length - 1);
Cache[cacheKey] = dpl_selectIndexStr;

}

private void GetCachedDropDownListSelectedIndex( )
{
string cacheKey = "Page" + GridView1.PageIndex.ToString();
if ((Cache[cacheKey] == null)||(Cache[cacheKey].ToString()==string.Empty))
{
return;
}
string dpl_selectIndexStr = Cache[cacheKey].ToString();
string[] selectedIndex = dpl_selectIndexStr.Split('|');

for (int i = 0; i <= CaculateLastRowIndex(); i++)
{
((DropDownList)(this.GridView1.Rows[i].FindControl("TestDDL"))).SelectedIndex = int.Parse(selectedIndex[i]);
Response.Write(((DropDownList)(this.GridView1.Rows[i].FindControl("TestDDL"))).SelectedIndex.ToString());

}

}

protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.CachDropDownListSelectIndex();//换页以前的PageIndex
GridView1.PageIndex = e.NewPageIndex;
bind();

}

protected void PageIndexChanged(object sender, EventArgs e)
{
this.GetCachedDropDownListSelectedIndex(); //换页以后的PageIndex
}
}
[code=HTML]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
PagerSettings-Mode="NumericFirstLast" AllowPaging="True"
OnPageIndexChanging="PageIndexChanging" OnPageIndexChanged="PageIndexChanged">

<Columns>
<asp:BoundField DataField="CompanyName" HeaderText="公司名称" />
<asp:BoundField DataField="ContactName" HeaderText="联系人" />
<asp:BoundField DataField="Phone" HeaderText="联系电话" />
<asp:TemplateField HeaderText="测试DropDownList" ShowHeader= "true">
<ItemTemplate>
<asp:DropDownList ID="TestDDL" runat="server">
<asp:ListItem Value="1" Text="One" />
<asp:ListItem Value="2" Text="Two"/>
<asp:ListItem Value="3" Text="Three" />
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>


[/code]
masterkill 2009-03-09
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 jijunwu 的回复:]
将数据绑定 写到分页事件里面
[/Quote]
分页事件里面肯定也有写绑定数据啊
  • 打赏
  • 举报
回复
将数据绑定 写到分页事件里面
zzxap 2009-03-09
  • 打赏
  • 举报
回复
你把全部数据放在另外一个dataset中,在导出到excel,就不用考虑分页的问题了
liuyeede 2009-03-09
  • 打赏
  • 举报
回复
在PageIndexChanging里调用第一个,在PageIndexChanged里调用第二个,调用第二个方法时注意要判断一下:对应的Session里是否有值。如果没有值则返回,说明是第一次到导航到改变后的页面。如果有值则调用。调用第一个方方法时也要判断对应的Session中是否有值,如果有值,则清空对应页的Session后再调用第一个方法。
臭你个臭臭 2009-03-09
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 liuyeede 的回复:]
看8楼回复,兄弟。红色的部分。
[/Quote]
额,我是那样的,提示SelectedIndex未定义
然后改成:

DropDownList ss=(DropDownList)(this.GridView1.Rows[i].Cells[2].FindControl("dpl"));
ss.SelectedIndex=int.Parse(selectedIndex[i]);

就好了

现在开始考虑哪里调用- -#
liuyeede 2009-03-09
  • 打赏
  • 举报
回复
看8楼回复,兄弟。红色的部分。
masterkill 2009-03-09
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 liuyeede 的回复:]
因为FindControl的返回类型是Control类型,所以在的到他的返回值是需要强制转换到DropDownList类型。
[/Quote]
请问selectedIndex未定义这个问题应该怎么解决呢?
liuyeede 2009-03-09
  • 打赏
  • 举报
回复
因为FindControl的返回类型是Control类型,所以在的到他的返回值是需要强制转换到DropDownList类型。
liuyeede 2009-03-09
  • 打赏
  • 举报
回复
(DropDownList)(this.GridView1.Rows[i].FindControl("dpl")).SelectedIndex=int.Parse(selectdIndex[i]);
liuyeede 2009-03-09
  • 打赏
  • 举报
回复
private void GetCacheDropDownListSelectedIndex(int pageIndex,int pageCount,int pageSize)
{
int allRowCounts=pageSize*pageCount;
int currentPageFirstRowIndex=(pageIndex==0)?pageSize*pageIndex:pageSize*pageIndex-1;
int currentPageLastRowIndex=(pageCount>=currentPageFirstRowIndex+pageCount)?(allRowCount-1):(currentPageFirstRowIndex+pageCount-1);
string cacheKey="page"+pageIndex.ToString();
string dpl_selectedIndexStr=Cache[cacheKey].ToString();
string[] selectedIndex=dpl_selectIndexStr.Split('|');
for(int i=currentPageFirstRowIndex;i<=currentPageLastRowIndex;i++)
{
(DropDownList)(this.GridView1.Rows[i].FindControl("dpl")).SelectedIndex=int.Parse(selectdIndex[i]);
}
}
masterkill 2009-03-09
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 wuyq11 的回复:]
选择deopdownlist时,把值赋值给变量或hiddenfiled控件,实现分页时保存值。
[/Quote]
以下代码您要有空的话请帮看看有什么错,特别是第二段
//保存每一页的DropDownList的SelectedIndex

private void CachDropDownListSelectedIndex(int pageIndex,int pageCount,int pageSize)
{
string dpl_selectIndexStr=string.Empty;
int allRowCounts=pageSize*pageCount;
int currentPageFirstRowIndex=pageSize*pageIndex;
int currentPageLastRowIndex=(pageCount>=currentPageFirstRowIndex+pageCount)?allRowCounts:(currentPageFirstRowIndex+pageCount);
string cacheKey="page"+pageIndex.ToString();
for(int i=currentPageFirstRowIndex;i<=currentPageLastRowIndex;i++)
{
dpl_selectIndexStr+=(DropDownList)(this.GridView1.Rows[i].FindControl("dpl"));
dpl_selectIndexStr=dpl_selectIndexStr.Substring(0,dpl_selectIndexStr.Length-2);
}
Cache[cacheKey]=dpl_selectIndexStr;
}
//获取每一页的保存的SelectedIndex并恢复原来的DropDownList的选项
private void GetCacheDropDownListSelectedIndex(int pageIndex,int pageCount,int pageSize)
{
int allRowCounts=pageSize*pageCount;
int currentPageFirstRowIndex=(pageIndex==0)?pageSize*pageIndex:pageSize*pageIndex-1;
int currentPageLastRowIndex=(pageCount>=currentPageFirstRowIndex+pageCount)?(allRowCount-1):(currentPageFirstRowIndex+pageCount-1);
string cacheKey="page"+pageIndex.ToString();
string dpl_selectedIndexStr=Cache[cacheKey].ToString();
string[] selectedIndex=dpl_selectIndexStr.Split('|');
for(int i=currentPageFirstRowIndex;i<=currentPageLastRowIndex;i++)
{
this.GridView1.Rows[i].FindControl("dpl").SelectedIndex=int.Parse(selectdIndex[i]);
}
}

提示说并不包含“SelectedIndex”的定义
还有就是,我应该在什么时候保存这个状态呢?在GridView1_PageIndexChanging中?那样的话要是只操作了第一页怎么办,那样的话在写入数据到excel档时,由于重新绑定数据一样不可以成功
wuyq11 2009-03-09
  • 打赏
  • 举报
回复
选择deopdownlist时,把值赋值给变量或hiddenfiled控件,实现分页时保存值。
wuyq11 2009-03-09
  • 打赏
  • 举报
回复
选择deopdownlist时,把值赋值给变量或hiddenfiled控件,实现分页时保存值。
德仔 2009-03-09
  • 打赏
  • 举报
回复
报什么错呀

62,046

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧