【发布时间】:2016-07-28 18:58:32
【问题描述】:
我在该行收到错误“输入字符串的格式不正确”:
int index = Convert.ToInt32(e.CommandArgument);
我的目标是从我的 Gridview(所选行的单元格 1)中获取 ID(字母和数字),以处理与该 ID 关联的数据库中的记录。
我发现的大多数页面都说使用上面的代码来查找gridview的行号。
我的aspx页面:
<asp:gridview ID="gridview1" runat="server" DataKeyNames="ID" AutoGenerateColumns="false" OnRowCommand="gridview1_RowCommand">
<columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btn_select" runat="server" Text="Select" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Record_ID" DataField="ID" />
<asp:BoundField HeaderText="Record_Date" DataField="Date" />
</Columns>
</asp:gridview>
我的代码背后:
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
//code stuff
final();
}
protected void final()
{
//code stuff for populating the gridview. Gridview populates as expected.
}
protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);//where I receive the error.
string id = gridview1.Rows[index].Cells[1].Text;
using (SqlConnection connection string)
{
try
{
cmd = new SqlCommand("DBSP", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@id", SqlDbType.Char).Value = id;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
final();
}
catch (Exception ex)
{
//code stuff
}
}
}
}
我尝试过的其他几件事来自:
Accessing GridView Cells Value
How to get cell value in GridView (WITHOUT using cell index)
Get the cell value of a GridView row
Getting value from a Gridview cell
以及其他人。
【问题讨论】:
-
你知道
e.CommandArgument的值是多少吗?听起来它可能包含一个或多个字母。如果是这种情况,您需要使用正则表达式或其他东西来隔离数字。 -
@EdPlunkett,是的,ID 的第一个字符是 alpha 字符。