In this article I will explain you how to modify select item in listview and update.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace ListViewModify
{
public partial class Form1 : Form
{
stringcon = “Data Source=PC-Name;Initial Catalog=Northwind;Integrated Security=True”;
public Form1()
{
InitializeComponent();
}
private voidForm1_Load(object sender, EventArgs e)
{
listView1.GridLines = true;
listView1.View = View.Details;
//Add Column Header
listView1.Columns.Add(“Employee ID”, 150);
listView1.Columns.Add(“First Name”, 150);
listView1.Columns.Add(“Last Name”, 150);
}
private voidbutton2_Click(object sender, EventArgs e)
{
// Chnage sql query and table name
string sql = “Select Employeeid,FirstName,LastName from Employees”;
SqlConnection cnn = new SqlConnection(con);
cnn.Open();
SqlCommand cmd=new SqlCommand(sql,cnn);
SqlDataReader Reader = cmd.ExecuteReader();
listView1.Items.Clear();
while (Reader.Read())
{
ListViewItem lv = new ListViewItem(Reader.GetInt32(0).ToString());
lv.SubItems.Add(Reader.GetString(1));
lv.SubItems.Add(Reader.GetString(2));
listView1.Items.Add(lv);
}
Reader.Close();
cmd.Dispose();
cnn.Close();
}
int sl = 0;
//retrive select item in listview and store in textbox3 and textbox4
private void listView1_SelectedIndexChanged(object sender, EventArgse)
{
var selectitem = listView1.SelectedItems;
sl = Convert.ToInt32(selectitem[0].Text);
ListViewItem lvitem = listView1.FindItemWithText(Convert.ToString(sl));
if (lvitem != null)
{
textBox3.Text=lvitem.SubItems[1].Text;
textBox4.Text = lvitem.SubItems[2].Text;
}
}
private voidbutton4_Click(object sender, EventArgs e)
{
//update by searching for text in subitmes.
ListViewItemlvitem = listView1.FindItemWithText( Convert.ToString(sl));
if(lvitem!=null)
{
lvitem.SubItems[1].Text = textBox3.Text ;
lvitem.SubItems[2].Text = textBox4.Text ;
listView1.Items[sl-1].BackColor = Color.BlueViolet;
}
}
}
}