C# listView, add icon to existing item - c#

I want to add small image to existing row i listView. ListView is connected to SQLite DB.
When select some row in listView and click on button "Zakoncz" there is added to SQLite DataBase value "1" to column "CzyZaznaczone" and when here is value "1" listView should add image to selected row.
My image is in resources, can I use that or only from file?
Now my code adds a value to the database but does not add an image.
Here is the code:
SQLiteConnection con = new SQLiteConnection("data source=baza.db");
SQLiteDataAdapter ada = new SQLiteDataAdapter("select * from Przypominacz", con);
SQLiteCommand cmd = con.CreateCommand();
var index = this.listView1.SelectedIndices[0];
string zaznaczone = this.listView1.Items[index].SubItems[0].Text;
con.Open();
cmd.CommandText = "UPDATE Przypominacz SET CzyZakonczone=1 WHERE Nazwa='"+ zaznaczone + "'";
cmd.ExecuteNonQuery();
//dodanie ikonki do zakonczonego zadania
bool result = false;
string sql = "SELECT * FROM Przypominacz WHERE CzyZaznaczone='1'";
SQLiteDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
result = true;
}
reader.Close();
bool rezultat = result;
if(rezultat==true)
{
for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
{
ImageList imageList = new ImageList();
imageList.Images.Add(Image.FromFile("D:\\C#\\Przypominacz2 — kopia (4)\\przypominacz\\przypominacz\\Resources\\checked.png"));
listView1.SmallImageList = imageList;
var listViewItem = listView1.Items.Add("Item with image");
}
}
Now looks:
Without img
But should looks like this:
With img

You are adding new ListViewItem to existing list instead of changing selected one(s). You can do it like this:
if(rezultat)
{
ImageList imageList = new ImageList();
imageList.Images.Add(Image.FromFile("D:\\C#\\Przypominacz2 — kopia (4)\\przypominacz\\przypominacz\\Resources\\checked.png"));
listView1.SmallImageList = imageList;
for (int i = 0; i < listView1.Items.Count; i++ )
{
if (listView1.Items[i].Selected)
listView1.Items[i].ImageIndex = 0;
}
}
To add image to ImageList from resources, take a look at this question

Related

How to add image to imagelist from database and show them on listview

I need to add all image of my books in SQL Server database to the imagelist and show them on listview, but when I run the program, it shows the first image and repeats it on another images but the id of the images is changing I don't know what the problem is.
Image of the program
Image of the program
And this is the code:
MySqlConnection msc = new MySqlConnection("server=localhost;database=listv;uid=root;");
MySqlCommand cmd = new MySqlCommand("select id,image from books");
msc.Open();
listView1.Clear();
ImageList images = new ImageList();
images.ColorDepth = ColorDepth.Depth32Bit;
listView1.LargeImageList = images;
listView1.LargeImageList.ImageSize = new System.Drawing.Size(255, 255);
cmd.Connection = msc;
MySqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
byte[] imagebyte = (byte[])(dr["image"]);
MemoryStream image_stream = new MemoryStream(imagebyte);
image_stream.Write(imagebyte, 0, imagebyte.Length);
images.Images.Add(dr["image"].ToString(), new Bitmap(image_stream));
image_stream.Close();
ListViewItem listItem = new ListViewItem();
listItem.Text = dr["id"].ToString();
listItem.ImageKey = dr["image"].ToString();
listView1.Items.Add(listItem);
}

Change color of Combobox item when item is already in a list

I have a list of combobox items generated from a database
private void Outlet1_DropDown(object sender, EventArgs e)
{
SqlDataReader dr7;
SqlConnection Conadd1 = new SqlConnection("Data Source=PC-PC\\MIKO;Initial Catalog=Caproj;Integrated Security=True;");
Conadd1.Open();
SqlCommand cmd6 = new SqlCommand("select Address from [Outlet Table] where ClientID='" + clientid + "'", Conadd1);
cmd6.Connection = Conadd1;
dr7 = cmd6.ExecuteReader();
DataTable dt8 = new DataTable();
dt8.Columns.Add("Address", typeof(string));
dt8.Load(dr7);
Outlet1.DisplayMember = "Address";
Outlet1.DataSource = dt8;
Conadd1.Close();
colorcombo();
}
A user can select a certain item in the said combobox and it will be inserted in a listbox. Once the listbox contains the said address, I want the item color to be made red, so it will remind the user that it's already selected
my attempt to code, I have no idea on how to use the drawmode event:
private void colorcombo()
{
if (outletlist.Items.Contains(Outlet1.Items.ToString()))
{
Con.Open();
for (int i = Outlet.Items.Count - 1; i >= 0; --i)
{
using (var cmd = new SqlCommand("UPDATE [Outlet Table] SET [Address] = Address WHERE [Address] = #address", Con))
{
cmd.Parameters.AddWithValue("#address", (Outlet.Items[i].Text));
if (cmd.ExecuteNonQuery() > 0)
{
//Outlet.Items[i].BackColor = Color.Red;
}
else
{
//Outlet.Items[i].BackColor = Color.Black;
}
}
}
}
}
Some details:
Outlet1 = name of my combobox
outletlist = name of my listbox

Cant display images in Listview from database mysql in c#

I couldn't display the images from my database in Listview although I can retrieve some data like my the title of it.
Check out my code:
public void LoadBooks()
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
connection.Open();
try
{
listView1.Clear();
ImageList myImageList1 = new ImageList();
myImageList1.ImageSize = new System.Drawing.Size(80, 80);
listView1.LargeImageList = myImageList1;
MySqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "Select * from booktable";
MySqlDataAdapter adap = new MySqlDataAdapter(cmd);
DataTable ds = new DataTable();
adap.Fill(ds);
foreach (DataRow dr in ds.Rows)
{
byte[] byteBLOBData = (byte[])dr["bookphoto"];
var stream = new MemoryStream(byteBLOBData);
Image bookimages= Image.FromStream(stream);
myImageList1.Images.Add(bookimages);
ListViewItem lsvparent = new ListViewItem();
lsvparent.Text = dr["booktitle"].ToString();
listView1.Items.Add(lsvparent);
}
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
Although the size of the image is showing in the Listview but there is any image just a blank image.
Hope you help me . Thank you
I don't see where you set the IamgeIndex that points to the ImageList.
It is a property of the ListViewItem and you can set it when adding it or at any time later on.
This will set it to the latest image in the list:
listView1.Items.Add(lsvparent, myImageList1.Image.Count - 1);
To change it later you can use:
listView1.Items[23].ImageIndex = 42;
or, if you have nice names:
listView1.Items[lsvparent].ImageIndex = 0;
Note that any ImageList is restricted to one Size, a maximum of 256x256 pixels and one bit depth fo all images!
It is a good idea to load a default image as the first one into the ImageList i.e. at index = 0 so you have a common one to fall back to.

DataGridViewComboBoxColumn save SelectedText for each row in SQL

This is T-SQL for Inserting data from datagridview into SQL Table but the issue is that one of datagridview's column is DataGridViewComboBoxColumnand I need for each row save particular selected item in combobox. May I ask how it can be done?
public DataGridViewComboBoxColumn cbColumn;
conn.Open();
SqlTransaction sqlTrans = conn.BeginTransaction();
try
{
string delCmdTxt = "DELETE FROM PRONAJEM WHERE NA_CISLKU=#NA_CISLKU";
SqlCommand cmdDel = conn.CreateCommand();
cmdDel.Parameters.AddWithValue("#NA_CISLKU",VybraneCisku);
cmdDel.CommandText = delCmdTxt;
cmdDel.Transaction = sqlTrans;
cmdDel.ExecuteNonQuery();
string insert_sql = "INSERT INTO PRONAJEM(DATUM,PLODINA,CENAMJ,MNOZSTVIMJ,PRIKAZ,NA_ZUSTA,NA_CISLKU,RODNECISLO)VALUES" +
"(#DATUM,#PLODINA,#CENAMJ,#MNOZSTVIMJ,#PRIKAZ,#NA_ZUSTA,#NA_CISLKU,#RODNECISLO)";
using (SqlCommand sqlcom = conn.CreateCommand())
{
sqlcom.CommandText = insert_sql;
sqlcom.Transaction = sqlTrans;
sqlcom.Parameters.Add("#DATUM", SqlDbType.Date); //Replace with whatever the correct datatypes are
sqlcom.Parameters.Add("#PLODINA", SqlDbType.NVarChar);
sqlcom.Parameters.Add("#CENAMJ", SqlDbType.Decimal);
sqlcom.Parameters.Add("#MNOZSTVIMJ", SqlDbType.Decimal);
sqlcom.Parameters.Add("#PRIKAZ", SqlDbType.Date);
sqlcom.Parameters.Add("#NA_ZUSTA", SqlDbType.Decimal);
sqlcom.Parameters.Add("#NA_CISLKU", SqlDbType.NVarChar);
sqlcom.Parameters.Add("#RODNECISLO", SqlDbType.NVarChar);
var validRows = dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => row.Cells["DATUM"].Value != null);
foreach (DataGridViewRow row in validRows)
{
sqlcom.Parameters[0].Value = row.Cells["DATUM"].Value;
sqlcom.Parameters[1].Value = row.Cells["POLOZKAcb"].Value;
sqlcom.Parameters[2].Value = row.Cells["CENAMJ"].Value;
sqlcom.Parameters[3].Value = row.Cells["MNOZSTVIMJ"].Value;
sqlcom.Parameters[4].Value = row.Cells["PRIKAZ"].Value;
sqlcom.Parameters[5].Value = row.Cells["NA_ZUSTA"].Value;
sqlcom.Parameters[6].Value = VybraneCisku;
sqlcom.Parameters[7].Value = VybraneRodneCislo;
sqlcom.ExecuteNonQuery();
}
sqlcom.Dispose();
}
sqlTrans.Commit();
This is the creating of DataGridViewComboBoxColumn:
string query = "SELECT * FROM PLODINY ";
SqlCommand newcom = new SqlCommand(query, conn);
conn.Open();
SqlDataReader reader= newcom .ExecuteReader();
List<string> listPlodiny = new List<string>();
while (reader.Read())
{
listPlodiny.Add(reader.GetString(reader.GetOrdinal("PLODINA")) + "-" + Decimal.Parse(reader["CENAZAQ"].ToString()).ToString());
for (int i = 0; i <= listPlodiny.Count() - 1; i++)
{
}
}
cbColumn = new DataGridViewComboBoxColumn();
cbColumn.DataSource = listPlodiny;
cbColumn.DropDownWidth = 100;
dataGridView1.Columns.Add(cbColumn);
cbColumn.DisplayIndex = 3;
cbColumn.HeaderText = "Položka";
cbColumn.DataPropertyName = "POLOZKAcb";
Thank you all for your time
I think because you not set a .ValueMember property for DataGridViewComboBoxColumn...
You need to set
.ValueMember - set Value for Cell from DataSource's property.
This value will be referenced with Column.DataPropertyName's value.
.DisplayMember- Value of this will be used for diplay text in dropdown cell
Try next(updated for using of DataTable as DataSource in DataGridViewComboBoxColumn:
DataTable dtPlodiny;
using(SqlConnection sqlConn = new SqlConnection(conn))//conn - your connection string
{
string sqlQuery = #"SELECT ID, Description FROM PLODINY"; //better practice use only fields you need
using(SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dtPlodiny);
}
}
cbColumn = new DataGridViewComboBoxColumn();
cbColumn.Name = "POLOZKAcb"
cbColumn.DataSource = dtPlodiny; //Changed with DataTable
//add next two rows
cbColumn.DisplayMember = "Description" //property from .Datasource you want to show for user
cbColumn.ValueMember = "ID" //property from .Datasource you want use as Value - reference to DataPropertyName
cbColumn.DropDownWidth = 100;
dataGridView1.Columns.Add(cbColumn);
cbColumn.DisplayIndex = 3;
cbColumn.HeaderText = "Položka";
cbColumn.DataPropertyName = "POLOZKAcb";
If your datagridview use always same columns,
then I think easally if you use a predefined columns(created/added through Designer). Then you can set a name for every column and use it in code as object:
this.MyColumnPolozka.Name...
for example...
if you donot get correct value from row.Cells(0).Value then try casting it to dropdownlist

I want to get or set data to each cell of DataGridView based on combobox selection

Please find my code , I need to know the relationship between combobox selection and datagridview. Basically if I set my area selection only those related to the Area shall be display not the whole database as I am getting now. Thanks.
private void RTUModification_Load(object sender, EventArgs e) {
//Select cell where checkbox to be display
Rectangle rect = this.rtumodDGV1.GetCellDisplayRectangle(0, -1, true);
chkbox.Size = new Size(18, 18);
//set position of header checkbox where to places
rect.Offset(4, 2);
chkbox.Location = rect.Location;
chkbox.CheckedChanged += rtucheckBoxCheckChanged;
//Add CheckBox control to datagridView
this.rtumodDGV1.Controls.Add(chkbox);
// Create new DataTable instance
dtDataTable = new System.Data.DataTable();
if (null == dtDataTable)
{
MessageBox.Show("Insufficient memory.", "ERROR");
}
//load the datable and fill them with value
strErrorMsg = Utilities.OpenSQLConnection(out m_SqlConn, true, false); //load normal database
if (false == string.IsNullOrEmpty(strErrorMsg))
{
MessageBox.Show(strErrorMsg, "SQL connection ERROR");
}
SqlDataAdapter sqlAdapter = null;
strSelectCmd = "SELECT Area_ID, StationId, SystemId, CCNumber, LineNumber, RTUNumber, SRTUNumber, Description, SDescription FROM RTU_ADDRESS";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = m_SqlConn;
sqlCmd.CommandText = strSelectCmd;
sqlAdapter = new SqlDataAdapter();
sqlAdapter.SelectCommand = sqlCmd;
strErrorMsg = Utilities.FillDataTable(m_SqlConn, strSelectCmd, dtDataTable);
if (string.IsNullOrEmpty(strErrorMsg) == false)
{
MessageBox.Show("Failed to retrieve information from database.", "ERROR");
dtDataTable.Dispose();
Utilities.CloseAndDisposeSQLConnection(m_SqlConn);
}
int iRetrievedNoOfRecords = dtDataTable.Rows.Count;
if (iRetrievedNoOfRecords > 0)
{
for (int i = 0; i < iRetrievedNoOfRecords; i++)
this.rtumodcomboBox.Items.Add((string)dtDataTable.Rows[i]["Area_ID"]);
}
strErrorMsg = Utilities.ExecuteSQLCommand(m_SqlConn, strSelectCmd);
if (string.IsNullOrEmpty(strErrorMsg) == false)
{
MessageBox.Show(this, "Error!Loading into RTU datagrid");
}
//load the datagridview header
rtumodDGV1.DataSource = dtDataTable;
}
Here's the sample code that you might need.
strSelectCmd = "SELECT Area_ID, StationId, SystemId, CCNumber, LineNumber, RTUNumber, SRTUNumber, Description, SDescription FROM RTU_ADDRESS where Area_ID="+cbxMyCombox.SelectedIndex;
other options other SelectedIndex could be SelectedItem or SelectedValue . Depending upon what you are using. Which is unclear right now.

Categories

Resources