我需要在C#
中的ListView中单击列我有一些来自How to determine the clicked column index in a Listview的示例代码,但我不确定应该如何实现它。
答案 0 :(得分:18)
Jeez,每个人都懒得发布代码。该过程分为三个步骤:
Control.MousePosition
获取鼠标位置并转换为客户端坐标。HitTest
函数以查找鼠标指向的内容。这将返回一个包含大量信息的对象,但实际的列号除外...... IndexOf
搜索子项目数组以查找列号。以下是代码:
private void listViewMasterVolt_DoubleClick(object sender, EventArgs e)
{
Point mousePosition = myListView.PointToClient(Control.MousePosition);
ListViewHitTestInfo hit = myListView.HitTest(mousePosition);
int columnindex = hit.Item.SubItems.IndexOf(hit.SubItem);
}
答案 1 :(得分:4)
ListView
控件使用HitTest
方法。你给它鼠标点击事件的x和y坐标,它给你一个对象,告诉你那一行(列表视图项)和列(列表视图子项)。
答案 2 :(得分:1)
e.Column实际上持有索引
private void lv_ColumnClick(object sender, ColumnClickEventArgs e)
{
Int32 colIndex = Convert.ToInt32(e.Column.ToString());
lv.Columns[colIndex].Text = "new text";
}
答案 3 :(得分:0)
这是VB.NET代码,但对象应该是相同的。
Private LVUsersLastHit As Point
Private Sub lvUsers_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvUsers.MouseUp
Me.LVUsersLastHit = e.Location
End Sub
Private Sub LvUsers_Doubleclick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvUsers.DoubleClick
Dim HTI As ListViewHitTestInfo = Me.lvUsers.HitTest(Me.LVUsersLastHit)
If HTI.Item Is Nothing OrElse HTI.SubItem Is Nothing Then Exit Sub 'nothing was dblclicked
MsgBox("doubleClicked the " & HTI.Item.ToString & " Item on the " & HTI.SubItem.ToString & " sub Item")
End Sub