我正在尝试使用GridView
验证onRowCommand
当我选择一个按钮时,它需要验证行delivery date
并在无效时显示内联错误消息。
目前,我的GridView
设置如下:
<asp:GridView ID="gvDistribution" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1000px" DataKeyNames="id" AllowPaging="True" OnPageIndexChanging="gvDistribution_PageIndexChanging" PageSize="5" OnRowCommand="gvDistribution_OnRowCommand" OnRowDataBound="gvDistribution_RowDataBound">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="name" HeaderText="Beneficiary Name"></asp:BoundField>
<asp:BoundField DataField="packingDate" HeaderText="Packing Date" DataFormatString="{0:dd/M/yyyy}"></asp:BoundField>
<asp:BoundField DataField="deliveryDate" HeaderText="Delivery Date" DataFormatString="{0:dd/M/yyyy}" />
<asp:TemplateField HeaderText="Status" ItemStyle-Width="120px">
<ItemTemplate>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="View" Text="View Details" />
<asp:ButtonField CommandName="Action" Text="Action" />
<asp:TemplateField HeaderText="" ItemStyle-Width="120px">
<ItemTemplate>
<asp:Label ID="lblError" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
GridView
onRowCommand
背后的代码:
protected void gvDistribution_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int rowNo = int.Parse(e.CommandArgument.ToString());
string distributionID = this.gvDistribution.DataKeys[rowNo].Value.ToString();
if (e.CommandName == "View")
{
Response.Redirect("PackingDetails.aspx?id=" + distributionID);
}
else if(e.CommandName == "Action")
{
DistributionPacking distPack = new DistributionPacking();
distPack = packBLL.getDateDetailByDistributionID(distributionID);
DateTime deliveryDate = distPack.deliveryDate;
foreach (GridViewRow g in gvDistribution.Rows)
{
if (deliveryDate > DateTime.Today)
{
Label lblError = (Label)g.FindControl("lblError");
lblError.Text = "Delivery date has not reach yet!";
}
else
{
bool result = packBLL.updateDeliveryStatus(distributionID);
if (!result)
{
//Call the retrieve all distributions without any filtering again
List<DistributionPacking> allDistribution = new List<DistributionPacking>();
allDistribution = packBLL.getAllDistribution();
gvDistribution.DataSource = allDistribution;
gvDistribution.DataBind();
}
}
}
}
}
问题是,当delivery date
得到验证时,每一行中都会显示一条错误消息,而不仅仅是需要验证的消息。
有人可以告诉我如何在验证的行中强制只发送一条消息吗?
答案 0 :(得分:3)
然后替换以
开头的循环foreach (GridViewRow g in gvDistribution.Rows){}
与
if(gvDistribution.SelectedRow != null)
{
if (deliveryDate > DateTime.Today)
{
Label lblError = (Label)gvDistribution.SelectedRow.FindControl("lblError");
lblError.Text = "Delivery date has not reach yet!";
}
else
{
// ...
}
}