从DataGridView获取所选行的单元格的内容

时间:2015-09-30 04:18:59

标签: c# asp.net gridview

string FeeId = grdvw.Rows[index].Cells[0].Text;

这是检索所选行中单元格内容的正确方法吗?如果我使用它,我就没有价值。所以,请建议最佳方式。

3 个答案:

答案 0 :(得分:1)

是的,这是一种方法,您也可以这样做:

string FeeId = grdvw.Rows[index].Cells[0].Value;

另外,如果你想从所有行中获取值,你可以像这样迭代Datagridview:

foreach (DataGridViewRow row in grdvw.Rows)
{
   string column0 = row.Cells[0].Value;
   string column1 = row.Cells[1].Value;
   //More code here
}

答案 1 :(得分:1)

我尝试时获得了价值。以下是我在运行时添加行和列的示例:

public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        DataColumn dCol1 = new DataColumn("Col1", typeof(System.String));
        DataColumn dCol2 = new DataColumn("Col2", typeof(System.String));
        dt.Columns.Add(dCol1);
        dt.Columns.Add(dCol2);
        for (int i = 0; i < 2; i++)
        {
            DataRow row1 = dt.NewRow();
            row1["Col1"] = "One";
            row1["Col2"] = "Two";
            dt.Rows.Add(row1);
        }
        foreach (DataColumn col in dt.Columns)
        {
            BoundField bField = new BoundField();
            bField.DataField = col.ColumnName;
            bField.HeaderText = col.ColumnName;
            GridView1.Columns.Add(bField);
        }
        GridView1.DataSource = dt;
        //Bind the datatable with the GridView.
        GridView1.DataBind();
        string str = GridView1.Rows[0].Cells[0].Text;
    }
}

答案 2 :(得分:0)

public void testMethod() {
    String myArray[] = new String [] { "cook", null, "chef", "baker", null, null, "butcher", null, "distiller" };
    for (int i = 0, count = 0; i < myArray.length; i++) {
        if (myArray[i] != null) 
            System.out.println((++count) + ". " + myArray[i]);
    }   
}

如果我们这样使用,我们就会得到答案