我已经编写了这段代码来创建一个包含3列的网格视图
DataTable dt = new DataTable();
dt = new DataTable();
dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price(Grouch)/Hectares", typeof(float));
DataColumn[] keys = new DataColumn[2];
keys[0] = dt.Columns["ID"];
dt.PrimaryKey = keys;
dt.Rows.Add("1", "Seaside Location", 1.5);
Session[key] = dt;
return dt;
我想在此代码中添加一个包含数量的文本框。
当我在另一个文本框中给出我想要的数量时,可以得到总数。
例如2 * 1.5 = 3
我该怎么做?
我的一个大问题是我不知道如何取第3列的值。本例中的值为1.5。
答案 0 :(得分:0)
要从第三列获取值,您可以迭代该数组:
GridView.Rows[index].Cells[2].Value.ToString());
示例:
String TextIn4thRow3rdColumn = myGridView.Rows[3].Cells[2].Value.ToString());
答案 1 :(得分:0)
如果我理解正确,您需要价格列中的TextBox和总价格的文本框。您可以使用TemplateColumn在文本框中显示价格,使用页脚显示总价。
ASPX:
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField HeaderText="ID" DataField="Name" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:TemplateField HeaderText="Price(Grouch)/Hectares">
<ItemTemplate>
<asp:TextBox ID="TxtPrice" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtTotal" runat="server" Text="0"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
对不起VB.Net,我希望你看到我的意思,导入部分在GridView的RowDataBound中:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim dt As New DataTable
dt.Columns.Add("ID", GetType(Int32)).AutoIncrement = True
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Price(Grouch)/Hectares", GetType(Single))
dt.PrimaryKey = New DataColumn() {dt.Columns("ID")}
Dim newRow As DataRow = dt.NewRow
newRow("ID") = 1
newRow("Name") = "Seaside Location"
newRow("Price(Grouch)/Hectares") = 1.5
dt.Rows.Add(newRow)
newRow = dt.NewRow
newRow("ID") = 2
newRow("Name") = "City Location"
newRow("Price(Grouch)/Hectares") = 7.9
dt.Rows.Add(newRow)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Sub
Private totalPrice As Single = 0
Private Sub GridRowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim row As DataRow = DirectCast(e.Row.DataItem, DataRowView).Row
Dim txtPrice As TextBox = DirectCast(e.Row.FindControl("TxtPrice"), TextBox)
Dim price As Single = DirectCast(row("Price(Grouch)/Hectares"), Single)
txtPrice.Text = price.ToString
totalPrice = totalPrice + price
ElseIf e.Row.RowType = DataControlRowType.Footer Then
Dim txtTotal As TextBox = DirectCast(e.Row.FindControl("TxtTotal"), TextBox)
txtTotal.Text = totalPrice.ToString
End If
End Sub