我在ASP.NET Web应用程序中有一个GridView,其中我在每行中添加了按钮:
<asp:GridView ID="gridviewdatadosen" runat="server" AutoGenerateColumns="False" CssClass="table table-striped table-bordered table-hover" OnRowDataBound="gridviewdatadosen_RowDataBound" OnSelectedIndexChanged="gridviewdatadosen_SelectedIndexChanged" OnRowCommand="gridviewdatadosen_RowCommand">
<Columns>
<asp:BoundField DataField="NIK" HeaderText="NIK" SortExpression="NIK"></asp:BoundField>
<asp:BoundField DataField="NIDN" HeaderText="NIDN" SortExpression="NIDN"></asp:BoundField>
<asp:BoundField DataField="NAMA" HeaderText="NAMA" SortExpression="NAMA"></asp:BoundField>
<asp:BoundField DataField="Alamat" HeaderText="Alamat" SortExpression="Alamat"></asp:BoundField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:Button ID="btnstatus" runat="server" Text="Aktif" CssClass="btn btn-primary" CommandName="aktifasi" CommandArgument='<%# Eval("NIK") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
我在服务器端填写datagridview。我填写了数据库中的数据。
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
SqlConnection conn = new SqlConnection(@"Data Source=localhost;Initial Catalog=SKRIPSI;User ID=sa;Password=sa");
conn.Open();
string ngisi = "SELECT [nik] as 'NIK' , [nidn] as 'NIDN', [nama] as 'NAMA', [alamat] as 'Alamat' FROM [dosen]";
SqlCommand comm = new SqlCommand(ngisi, conn);
dt.Load(comm.ExecuteReader());
conn.Close();
gridviewdatadosen.DataSource = dt;
gridviewdatadosen.DataBind();
int tmp = dt.Rows.Count;
在填写datagridview之后,我想通过选择id和状态为dosen来检查他是否处于活动状态。
conn.Open();
string check = "SELECT nik, status FROM [dosen]";
comm = new SqlCommand(check, conn);
dt1.Load(comm.ExecuteReader());
conn.Close();
我尝试更改按钮上的现有文字,但没有成功。
for (int i = 0; i < tmp; i++)
{
if (dt1.Rows[i][1].ToString() == "Aktif")//check the dosen aktif or not
{
for (int j = 0; j < tmp; j++)
{
if (dt.Rows[j][0].ToString() == dt1.Rows[i][0].ToString())// check nik where status = 'Aktif'
{
// I want to change the button in each row. if he 'Aktif' then the text in button will change to be 'aktif'
//do not know what to do
}
}
}
}
我想更改每行中的按钮。如果他'Aktif'那么按钮中的文字将变为'aktif'。帮我解决这个问题。对不起,如果我的英语或我的解释很糟糕。谢谢
答案 0 :(得分:0)
您可以循环所有行,找到按钮并根据dt1
foreach (GridViewRow row in GridView1.Rows)
{
//find the button in the row with findcontrol and cast back to a button
Button button = row.FindControl("btnstatus") as Button;
//check dt1 and set button text
button.Text = "Active";
}
或者您可以使用OnRowDataBound
事件在GridView数据绑定上执行相同的操作。
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//find the button in the row with findcontrol and cast back to a button
Button button = e.Row.FindControl("btnstatus") as Button;
//check dt1 and set button text
button.Text = "Active";
}
}