我正在尝试在asp datalist中放置一个asp gridview。对于datalist中的每个项目,我希望返回另一个数据库表中的某些值。
我编写了以下代码,但gridview不返回数据(我可以确认数据库中有记录,存储过程是否正确)。 asp datalist工作正常。
如果没有填充gridview,我做错了什么?
<asp:DataList runat="server" id="listResponses" DataKeyField="QuestionID" CssClass="confirm" OnItemDataBound="listResponses_ItemDataBound">
<ItemTemplate>
<h3 class="confirm new">Question <asp:Label ID="lblaOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label></h3>
<div class="confirm_question">
<asp:Label ID="lblOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label>
<p class="confirm"><%# DataBinder.Eval(Container.DataItem, "QuestionText") %></p>
</div> <!-- end confirm_question -->
<asp:GridView runat="server" ID="gridResponses" DataKeyNames="QuestionID"">
<Columns>
<asp:BoundField DataField="AnswerTitle" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="Responses" HeaderText="Response Count" HeaderStyle-Width="150px" />
</Columns>
</asp:GridView>
</ItemTemplate>
</asp:DataList>
这是背后的代码。
public partial class questionnaire_responses : System.Web.UI.Page
{
OsqarSQL GetData;
DataTable DT;
private string _productConnectionString;
private SqlConnection _productConn;
protected void Page_Load(object sender, EventArgs e)
{
string questionnaireId = Session["qID"].ToString();
int qid = Convert.ToInt32(questionnaireId);
GetData = new OsqarSQL();
string name = GetData.GetQuestionnaireName(qid);
lblQuestionnaireName.Text = name;
if (!IsPostBack)
{
DT = GetData.GetQuestionNameDataList(qid);
listResponses.DataSource = DT;
listResponses.DataBind();
}
}
private void BindGrid(GridView GridView, int questionId)
{
DataTable dt = new DataTable();
GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;
GridView.DataBind();
}
protected void listResponses_ItemDataBound(object sender, DataListItemEventArgs e)
{
GridView gridResponses=(GridView)e.Item.FindControl("gridResponses");
BindGrid(gridResponses, (int)listResponses.DataKeys[e.Item.ItemIndex]);
}
}
//Method from the data access class
public DataTable GetAnswerTitle(int QuestionId)
{
string returnValue = string.Empty;
SqlCommand myCommand = new SqlCommand("GetAnswer", _productConn);
myCommand.CommandType = CommandType.StoredProcedure;
,yCommand.Parameters.Add(new SqlParameter("@QUESTION_ID", SqlDbType.Int));
myCommand.Parameters[0].Value = QuestionId;
return createDataTable(getData(myCommand));
}
答案 0 :(得分:3)
您为GridView创建了一个空的DataTable DataSource
。
替换
DataTable dt = new DataTable();
GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;
用这个
DataTable dt = GetData.GetAnswerTitle(questionId);
GridView.DataSource = dt;