UkoM
UkoM

Reputation: 305

Getting selected value from ListView

On button click I want to get a value from a ListView column. I have tried using DataRow but I am getting NullReferenceExpection.

int row = listView.SelectedIndex;
DataRow dr = listView.Items.GetItemAt(row) as DataRow;
long ID = Convert.ToInt64(dr["ID"]);
TextBoxID.Text = ID.ToString();

Upvotes: 0

Views: 3323

Answers (2)

Muhammad Abbas
Muhammad Abbas

Reputation: 409

I read the answer above but it was ambiguous so now I am giving the full code to do the job.

        int index = list_View.SelectedIndex;
        DataRowView CompRow;
        long KOT;
        CompRow = list_View.Items.GetItemAt(index) as DataRowView;
        KOT = Convert.ToInt16(CompRow["KOT"]);
        MessageBox.Show(KOT.ToString());

Upvotes: 1

adv12
adv12

Reputation: 8551

ListView.GetItemAt() returns a ListViewItem. If you try to cast that to a DataRow via as, you'll get a null because that's what as returns when you try to cast to the wrong type. Use ListViewItem where you've used DataRow, and use the SubItems list to get field values. Also note that GetItemAt() returns null if there's no item at the specified index.

Upvotes: 0

Related Questions