简体   繁体   中英

Show the selected row record in textbox/label

How do I make the selected row record from a DataGridView show in a TextBox ? I got some TextBox and Label in a Form . I want the text inside the TextBox/Label to change when the user selects a row record from the DataGridView . I tried the following code to make it happen, but it doesn't work

private void ItemTable_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    label_itemid_show.Text = ItemTable.Rows[e.RowIndex].Cells[0].Value.ToString();
    text_itemname.Text = ItemTable.Rows[e.RowIndex].Cells[1].Value.ToString();
    text_itemprice.Text = ItemTable.Rows[e.RowIndex].Cells[2].Value.ToString();
    text_itemstock.Text = ItemTable.Rows[e.RowIndex].Cells[3].Value.ToString();
}

I'm working on a project that includes a features similar to yours. Currently I select a record in a datagridview and need to show it's values to textboxes so that any values can be edited.

This is how I tackle the problem.

Models.Item item = DAL.ItemDAL.GetItem(Convert.ToInt32(ItemDataGrid.CurrentRow.Cells[0].Value));
        tbModifyItemID.Text = Convert.ToString(item.ItemID);
        tbModifyItemName.Text = item.ItemName;

It's the ItemDataGridView.CurrentRow.Cells[0].Value that finds me the ItemID of the selected record.

In your case it's [DataGridName].CurrentRow.Cells[FieldNo, starting at 0].Value.ToString();

This allows you to click on any cell in the record and still retrieve the specified cell in the code.

Hope it helps c:

PS: If you put it inside a

private void ItemDataGrid_SelectionChanged(object sender, EventArgs e)

method it will run the code anytime you click a different cell in the datagridview.

You can use the following:

lblDetails.Text = dgMainGrid.SelectedRows[0].Cells[1].Value.ToString();

lblDetails: A label on the form. dgMainGrid: DataGrivView on the form.

PS: Just make sure you select the row inside the datagrid and not any particular cell, row selecting is done by clicking on the left of your first column ie the row selector column which gets added at the run time in WinForms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM