SelectedIndex在页面加载时自动选择

时间:2012-05-16 16:06:21

标签: asp.net

我有一个帐户页面,用户可以在其中查看他们的帐户信息。我希望他们能够在此处更改密码。我设法实现它的方式如下:

网络服务:

[WebMethod]
    public string ChangePassword(DataSet ds)
    {
        string database = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|/dvd_forum.accdb;Persist Security Info=True";
        OleDbConnection myConn = new OleDbConnection(database);
        OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from Users", myConn);
        OleDbCommandBuilder builder = new OleDbCommandBuilder(myDataAdapter);
        builder.QuotePrefix = "[";
        builder.QuoteSuffix = "]";
        myConn.Open();
        myDataAdapter.Update(ds, "Users");
        myConn.Close();
        return "Password changed!";
    }

前码:

<asp:Label ID="username" runat="server" Text=""></asp:Label><span>'s Account</span><br />
<asp:TextBox ID="ChangePasswordInput" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Save" 
    onclick="ChangePassword_Click" />
<asp:Label ID="Label2" runat="server" Text=""></asp:Label><asp:RequiredFieldValidator id="RequiredFieldValidator3" runat="server" ErrorMessage="Required!" ControlToValidate="ChangePasswordInput"></asp:RequiredFieldValidator>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>

返回代码:

public partial class Account : System.Web.UI.Page
{

public static DataSet ds;

protected void Page_Load(object sender, EventArgs e)
{
    if (User.Identity.IsAuthenticated)
    {
        username.Text = User.Identity.Name;
    }

    localhost.Service1 myws = new localhost.Service1();
    ds = myws.GetUserAcc(User.Identity.Name);
    GridView1.DataSource = ds;
    GridView1.DataBind();
}
protected void ChangePassword_Click(object sender, EventArgs e)
{
    //change password
    int i = GridView1.SelectedIndex;
    ds.Tables["Users"].Rows[i]["password"] = ChangePasswordInput.Text;
    GridView1.DataSource = ds;
    GridView1.DataBind();
    localhost.Service1 myws = new localhost.Service1();
    Label2.Text = myws.ChangePassword(ds);
}
}

这个问题是我必须在更改密码之前选择gridview中的行。有没有什么方法可以自动选择行,因为只有一行..或者如何在不先选择行的情况下以不同的方式对其进行编码?

感谢。

1 个答案:

答案 0 :(得分:0)

您的GridView和按钮是页面上的单独控件,因此您无法在不选择GridView中的行的情况下确定选择哪个用户进行密码更改。如果您可以将按钮放在GridView中,IMO会更好。制作editable GridView

编辑:根据您的评论,您的网格视图中只有一行,我真的没有看到将Gridview与数据表一起使用的原因。您可以使用标签显示用户名和新密码的文本框。 (您可能想再次确认密码)。然后在您的Web服务中,您可以传递新密码(如果已加密则更好),然后使用SQL Update语句更新数据,而不是传递数据。但是如果您仍然想要使用GridView,那么您可以直接在Row索引中传递0而不是获取selectedIndex。您可以检查dataTable是否包含任何行。

if(ds.Tables.Count > 0 && ds.Tables["Users"] != null && ds.Tables["Users"].Rows.Count > 0)
{
    ds.Tables["Users"].Rows[0]["password"] = ChangePasswordInput.Text;
    GridView1.DataSource = ds;
    GridView1.DataBind();
    localhost.Service1 myws = new localhost.Service1();
    Label2.Text = myws.ChangePassword(ds);
}
相关问题