how can I change the character casing in my listview to uppercase? the items in listview should be in uppercase when I choose uppercase in combobox. I hope someone can help me with this. Thanks in advance.
private void Form1_Load(object sender, EventArgs e)
{
showlv("SELECT a.customer_name, a.address, b.product_name, b.price FROM tbl_customer AS a INNER JOIN tbl_transaction AS b WHERE a.customer_code = b.customer_code", lvcust);
}
private void showlv(string sql, ListView lv)
{
try
{
lvcust.View = View.Details;
lvcust.FullRowSelect = true;
lvcust.GridLines = true;
conn.Open();
MySqlDataAdapter sda = new MySqlDataAdapter(sql, conn);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];
ListViewItem lvitem = new ListViewItem(dr["customer_name"].ToString());
lvitem.SubItems.Add(dr["address"].ToString());
lvitem.SubItems.Add(dr["product_name"].ToString());
lvitem.SubItems.Add(dr["price"].ToString());
lvcust.Items.Add(lvitem);
}
string[] column = new string[4] { "Customer Name", "Address", "Product Name", "Price" };
for (int x = 0; x < column.Length ; x++)
{
lvcust.Columns.Add(column[x]);
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedItem.Equals("Ascend"))
{
lvcust.Sorting = SortOrder.Ascending;
}
else if (comboBox1.SelectedItem.Equals("Descend"))
{
lvcust.Sorting = SortOrder.Descending;
}
else if (comboBox1.SelectedItem.Equals("Uppercase"))
{
//code to uppercase items in listview
}
}
You would be better off adding your case changing method in the event handler for the checkbox to upload it.
So, you doubleclick the checkbox control, then you iterate through the items in the combobox, then on each iteration set the content of the item to itself, with a .ToUpper() at the end.
I'm assuming you want to uppercase the customer name only. The trick is to store the original value as the tag of the ListItem. That way you can change the Text back to the original (non-uppercase) value later if you wanted. So in your code, find the first line and add the second below:
ListViewItem lvitem = new ListViewItem(dr["customer_name"].ToString());
lvitem.Tag = dr["customer_name"].ToString();
Now that you have that, here's the for loop to convert it to upper case:
ListViewItemCollection items = lvcust.Items;
for(int i=0;i<items.Count;i++){
ListViewItem item = items.Item[i];
object tag = item.Tag;
if(tag is string){
item.Text = ((string)tag).ToUpper();
}
}
This was all done off the top of my head in a text editor so there may be a syntax issue here or there but the logic should be correct.
Related
I am trying to output my selected rows in the AspxGridView to a label to see what has been selected. However the result is "System.Collections.Generic.List`1[System.Object]" Rather than the text in column called "ID"
protected void Button13_Click(object sender, EventArgs e)
{
List<string> itemList = new List<string>();
Label2.Text = string.Empty;
for (int i = 0; i < ASPxGridView1.VisibleRowCount; i++)
{
if (ASPxGridView1.Selection.IsRowSelected(i))
{
itemList.Add(ASPxGridView1.GetSelectedFieldValues("ID").ToString());
}
}
Label2.Text = string.Join("<br />", itemList);
}
If you want to select one row only and get its values on a click, I advise you to use the FocusedRowChanged event of the ASPxGridView.
To use it, you first need to enable FocusedRow.
Then if you want "ID" only, you can select it directly
Label2.Text = string.Join("<br />", ASPxGridView1.GetSelectedFieldValues("ID").ToString());
You can use :
foreach (var dt in ASPxGridView1.GetSelectedFieldValues("ID").ToList())
{
Label2.Text = Label2.Text + dt;
}
I have a DataGridView with a ComboBox column.
The ComboBox gets filled with a specific list of names and they are identical for every row in the DataGridView.
After I fill my DataGridView, I would like to do the following:
I want every Combo’s value to be set to the corresponding row’s “Table Columns” value, if exists.
I.e. in the picture above I want the value of the first Combo to be “id” (if it contains an item named “id”), the second to be “firstname”, etc.
If the value is not found, it should not select any value in the ComboBox.
Update: My current code that is not working
private void Mappings_Load(object sender, EventArgs e)
{
dgv.DataSource = tableColumns.Select(x => new { Value = x }).ToList();
dgv.Columns[0].HeaderText = "Table Columns";
DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
comboColumn.HeaderText = "File Columns";
foreach (var item in fileColumns)
comboColumn.Items.Add(item);
dgv.Columns.Add(comboColumn);
foreach(DataGridViewRow row in dgv.Rows)
{
string tableColumnValue = row.Cells[0].Value.ToString();
row.Cells[0].Value = tableColumnValue;
}
}
Trace the change .. you almost did it
private void Form1_Load(object sender, EventArgs e)
{
string[] tableColumns = new string[] { "A", "B", "C", "D" };
string[] fileColumns = new string[] { "A", "B", "C", "X" };
dgv.DataSource = tableColumns.Select(x => new { Value = x }).ToList();
dgv.Columns[0].HeaderText = "Table Columns";
DataGridViewComboBoxColumn comboColumn = new DataGridViewComboBoxColumn();
comboColumn.HeaderText = "File Columns";
foreach (var item in fileColumns)
comboColumn.Items.Add(item);
dgv.Columns.Add(comboColumn);
foreach (DataGridViewRow row in dgv.Rows)
{
string tableColumnValue = row.Cells[0].Value.ToString();
//Change is here
if (fileColumns.Any(i => i == tableColumnValue))
{
row.Cells[1].Value = tableColumnValue;
}
//end change
}
}
A while ago I did a similar thing:
Recognize which fields are of type enum
For the fiels of type enum, show a ComboBoxin the cell of the DataGridView (containing all the possible values of the enum) instead of the simple text field.
I think you only need to change certain parts of the code to transform it to what you are trying to achieve:
public partial class TableView<CollectionType, ItemType> : Form
{
public TableView(CollectionType elements)
{
InitializeComponent();
// custom:
this.DataGridView.DataSource = elements;
AdaptColumnsToColumnValueType();
}
private void AdaptColumnsToColumnValueType()
{
for (int columnIndex = 0; columnIndex < this.DataGridView.Columns.Count; columnIndex++)
{
var column = (DataGridViewColumn)this.DataGridView.Columns[columnIndex];
if (column.ValueType.IsEnum)
{
ReplaceColumnInDatagridView(
oldColumn: column,
newColumn: CreateComboBoxWithEnums(column));
}
}
}
private void ReplaceColumnInDatagridView(DataGridViewColumn oldColumn, DataGridViewColumn newColumn)
{
int columnIndex = oldColumn.Index;
this.DataGridView.Columns.Remove(oldColumn);
this.DataGridView.Columns.Insert(columnIndex, newColumn);
}
private DataGridViewComboBoxColumn CreateComboBoxWithEnums(DataGridViewColumn replacedEnumColumn)
{
var comboboxColumn = new DataGridViewComboBoxColumn();
comboboxColumn.DataSource = Enum.GetValues(replacedEnumColumn.ValueType);
comboboxColumn.DataPropertyName = replacedEnumColumn.DataPropertyName;
comboboxColumn.Name = replacedEnumColumn.Name;
return comboboxColumn;
}
}
you can use the DataGridViews RowsAdded event.
Edit: cmb is your ComboBoxColumn
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {
//Check if comboboxcolumn contains the value
if(cmb.Items.Contains(dataGridView1.Rows[e.RowIndex].Cells[0].Value)) {
//Set the value
dataGridView1.Rows[e.RowIndex].Cells["cmb"].Value = dataGridView1.Rows[e.RowIndex].Cells[0].Value;
}
}
I have a task to complete.. i must populate a list view from database and show in column wise and on a button click show it in a row wise... i just completed populating list view from database. now how do i display it it column wise and row wise... please help me...
This is the code i have tried to populate the database...
public partial class DtposMDIParentSystem : Form
{
List<object[]> result = new List<object[]>();
public DtposMDIParentSystem()
{
InitializeComponent();
//create the database connection
OleDbConnection aConnection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AP_AE\Desktop\DTPOS_APP\DataBase\DtposDatabase.accdb;");
//create the command object and store the sql query
OleDbCommand aCommand = new OleDbCommand("SELECT * FROM Food", aConnection);
try
{
aConnection.Open();
//create the datareader object to connect to table
OleDbDataReader reader = aCommand.ExecuteReader();
int i = 0;
while (reader.Read())
{
result.Add(new Object[reader.FieldCount]);
reader.GetValues(result[i]);
}
reader.Close();
aConnection.Close();
}
catch (InvalidOperationException ex)
{
MessageBox.Show("Invalid Masseage = " + ex.Message);
}
}
private void cmdOlives_Click(object sender, EventArgs e)
{
if (result.Count > 0)
{
string temp = "";
for (int i = 0; i < result[1].Length; i++)
{
temp += result[1][i] + " ";
}
TableOrderListView.Items.Add(temp);
}
}
}
You can achieve something like that by switching between different view modes:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
listView1.View = View.Details;
listView1.HeaderStyle = ColumnHeaderStyle.None;
listView1.Columns[0].Width = listView1.ClientSize.Width - 25;
listView1.Height = 244;
}
else
{
listView1.View = View.List;
listView1.Columns[0].Width = 50;
listView1.Height = 44;
}
}
You need to add one Column for Details view to work!
Note that you will have to adapt the size of the Listview:
In Details mode it will need to be tall enough to show several items
In List mode it will have to to rather wide but must not be tall enough to show more than one item (plus the scrollbar)!
If instead you mean to switch rows and columns you will have to do that in your datasource!
I am new to C#,this is my first project on C# language and my backend is Mysql, I am stuck at a particular point ,I am having a form which is containing a datagridview which is binded with database value,in that i have a column "TNS_Date" It is The Expiration Date of Product ,I want that if the TNS_Date is Greater then the Current Date so the Background Colour of that particular Cell Should Get Red in colured ,How could i do this ,please help me with this
I am using winforms and till now i had tried this
foreach (DataGridViewRow row in TNSFormdgv.Rows)
{
var now = DateTime.Now;
var expirationDate = DateTime.Parse(row.Cells[15].Value.ToString());
var OneMonthBefore = expirationDate.AddDays(-30);
if (now > OneMonthBefore && now < expirationDate)
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
else if (now > expirationDate)
{
row.DefaultCellStyle.BackColor = Color.Red;
}
}
when i am executing the Project i am getting this Error
Object reference not set to an instance of an object
This is my whole code for that particular form please check it where i am getting wrong
public partial class TNS_Subscription : Form
{
public TNS_Subscription()
{
InitializeComponent();
TNSSubscriptionForm();
}
private void TNSFormBackbtn_Click(object sender, EventArgs e)
{
new Form2().Show();
this.Hide();
}
public void TNSSubscriptionForm()
{
string ConString = "datasource=localhost;port=3306;username=root;password=ajay";
MySqlConnection conDataBase = new MySqlConnection(ConString);
MySqlCommand cmdDatabase = new MySqlCommand("Select acmecmpdetails.Cmp_Number,acmecmpdetails.Cmp_Name,acmecmpdetails.Cmp_AdminId,acmecmpdetails.Cmp_Address1,acmecmpdetails.Cmp_Country1,acmecmpdetails.Cmp_State1,acmecmpdetails.Cmp_City1,acmecmpdetails.Cmp_PostalCode,acmecmpdetails.Contact_Person1,acmecmpdetails.LandLine_Number1,acmecmpdetails.MobileNumber,acmecmpdetails.Cntct_Emailid,acmetally_detail.TallySerial_No,acmetally_detail.Tally_Release,acmetally_detail.Tally_Edition,acmetally_detail.TNS_Date,acmetally_detail.Tally_PrefPartner,acmetally_detail.Tally_accountId from acmesolutionsdatabase.acmecmpdetails INNER JOIN acmesolutionsdatabase.acmetally_detail ON acmesolutionsdatabase.acmecmpdetails.TallySerial_No= acmesolutionsdatabase.acmetally_detail.TallySerial_No;", conDataBase);
try
{
MySqlDataAdapter cddsda = new MySqlDataAdapter();
cddsda.SelectCommand = cmdDatabase;
DataTable dbdataset = new DataTable();
cddsda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
TNSFormdgv.DataSource = bsource;
cddsda.Update(dbdataset);
for(int i=0;i<TNSFormdgv.Rows.Count;i++)
{
if (Convert.ToDateTime(TNSFormdgv.Rows[i].Cells["TNS_Date"].Value.ToString()) > System.DateTime.Now.Date)
{
TNSFormdgv.Rows[i].Cells["TNS_Date"].Style.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Thanks In Advance
You could simply do this:
for(int i=0;i<MyGridView.Rows.Count;i++)
{
if (Convert.ToDateTime(MyGridView.Rows[i].Cells["TNS_Date"].Value.ToString()) > System.DateTime.Now.Date)
{
MyGridView.Rows[i].Cells["TNS_Date"].Style.BackColor = System.Drawing.Color.Red;
}
}
It will change the backcolor of the cell "TNS_Date" if its value is greater than current date.
OR
You can use the index of the column TNS_Date like:
If the index of the column TNS_Date is 3, then:
for(int i=0;i<MyGridView.Rows.Count;i++)
{
if (Convert.ToDateTime(MyGridView.Rows[i].Cells[3].Value.ToString()) > System.DateTime.Now.Date)
{
MyGridView.Rows[i].Cells[3].Style.BackColor = System.Drawing.Color.Red;
}
}
I hope it would solve the problem.
Here's sample that could help:
private void Form2_Load(object sender, EventArgs e)
{
dataGridView1.DataSourceChanged += dataGridView1_DataSourceChanged;
List<MyClass> list = new List<MyClass>();
list.Add(new MyClass { ID = 1, Name = "1", Date = DateTime.Now });
list.Add(new MyClass { ID = 2, Name = "2", Date = DateTime.Now });
list.Add(new MyClass { ID = 3, Name = "3", Date = DateTime.Now });
list.Add(new MyClass { ID = 4, Name = "4", Date = DateTime.Now.AddDays(1) });
dataGridView1.DataSource = list;
}
void dataGridView1_DataSourceChanged(object sender, EventArgs e)
{
// Loop through all the cells where date is in future
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((row.Cells[2].Value != null) && (DateTime)row.Cells[2].Value > DateTime.Now)
{
row.Cells[2].Style.BackColor = Color.Blue;
}
}
}
I am assuming that it's in Windows Forms as you are using datagridview.
For datagridview you'd be required to iterate through each cell of the grid to find the right cell and set the background colour.
I've created following code to do so.
void loadGrid()
{
DataTable dtData = new DataTable();
dtData.Columns.Add("TNS_Date");
DataRow dRow;
clmDate.DataPropertyName = "TNS_Date";
dRow= dtData.NewRow();
dRow["TNS_Date"] = "20-01-2014";
dtData.Rows.Add(dRow);
dRow = dtData.NewRow();
dRow["TNS_Date"] = "20-02-2014";
dtData.Rows.Add(dRow);
dRow = dtData.NewRow();
dRow["TNS_Date"] = "20-03-2014";
dtData.Rows.Add(dRow);
dgvGrid.DataSource = dtData;
for (int i = 0; i <= dgvGrid.RowCount - 1; ++i)
{
//Finding the right cell to change colour.
if(DateTime.Parse(dgvGrid["TNS_Date", i].Value.ToString()) >= DateTime.Now.Date)
dgvGrid[0, i].Style.BackColor = Color.Bisque;
}
}
If you are using asp.net datagridview then use a template field to do that. You can find more details about template field here : http://msdn.microsoft.com/en-us/library/aa479353.aspx
I have a listview which display the content from the database.I also have a refresh button in my form.Once the refresh button is clicked the listview is get updated once again.The problem is when the refresh button is clicked the already selected item in the listview is get removed from the focus.This is my code
private void btnRefresh_Click(object sender, EventArgs e)
{
//to refresh manually
this.Refresh();
listView1.Items.Clear();
/*btnEdit_Question.Enabled = true;
btnRepeat_Question.Enabled = true;
btnDelete_Question.Enabled = true;*/
GetData();
}
public void GetData()
{
try
{
now = DateTime.Now;
String time_date = now.ToString();
myConnection = new SqlConnection(connectString);
listView1.Items.Clear();
myConnection.Open();
String MyString1 = string.Format("SELECT " + data_variables.RES_TXT_STRING_COLUMN1 + "," + data_variables.RES_TXT_STRING_COLUMN2 + "," + data_variables.RES_TXT_STRING_COLUMN3 + "," + data_variables.RES_TXT_STRING_COLUMN4 + "," + data_variables.RES_TXT_STRING_COLUMN6 + " FROM " + data_variables.RES_TXT_STRING_QUESTION_TABLE);
com = myConnection.CreateCommand();
com.CommandText = MyString1;
dr = com.ExecuteReader();
ListViewItem itmX;
//Adding the Items To The Each Column
while (dr.Read())
{
itmX = new ListViewItem();
itmX.Text = dr.GetValue(0).ToString();
ListViewItem.ListViewSubItem aSubFooItem1 = new ListViewItem.ListViewSubItem(itmX, dr.GetValue(1).ToString()); //Creating subitems for the parent item
itmX.SubItems.Add(aSubFooItem1);
//Associating these subitems to the parent item
ListViewItem.ListViewSubItem aSubFooItem2 = new ListViewItem.ListViewSubItem(itmX, dr.GetValue(2).ToString()); //Creating subitems for the parent item
ListViewItem.ListViewSubItem aSubFooItem3 = new ListViewItem.ListViewSubItem(itmX, dr.GetValue(3).ToString()); //Creating subitems for the parent item
if (dr.GetValue(4).ToString() == "0")
{
aSubFooItem5 = new ListViewItem.ListViewSubItem(itmX, "No");
}
else
{
aSubFooItem5 = new ListViewItem.ListViewSubItem(itmX, "Yes");
}
if (dr.GetDateTime(2) < now && dr.GetDateTime(3) > now)
{
itmX.SubItems.Add(aSubFooItem2);
itmX.SubItems.Add(aSubFooItem3);
ListViewItem.ListViewSubItem aSubFooItem4 = new ListViewItem.ListViewSubItem(itmX, "In Progress");
itmX.SubItems.Add(aSubFooItem4);
itmX.SubItems.Add(aSubFooItem5);
}
else if (dr.GetDateTime(2) <= now)
{
itmX.SubItems.Add(aSubFooItem2);
itmX.SubItems.Add(aSubFooItem3);
ListViewItem.ListViewSubItem aSubFooItem4 = new ListViewItem.ListViewSubItem(itmX, "Expired");
itmX.SubItems.Add(aSubFooItem4);
itmX.SubItems.Add(aSubFooItem5);
}
else if (dr.GetDateTime(2) > now)
{
itmX.SubItems.Add(aSubFooItem2);
itmX.SubItems.Add(aSubFooItem3);
ListViewItem.ListViewSubItem aSubFooItem4 = new ListViewItem.ListViewSubItem(itmX, "Not Expired");
itmX.SubItems.Add(aSubFooItem4);
itmX.SubItems.Add(aSubFooItem5);
}
//add all the items ti listview
listView1.Items.Add(itmX);
//Adding colors
itmX.UseItemStyleForSubItems = false;
foreach (ListViewItem lvi in listView1.Items)
{
if (lvi.SubItems[4].Text=="Expired")
{
lvi.SubItems[4].BackColor = Color.Red;
}
else if (lvi.SubItems[4].Text == "Not Expired")
{
itmX.SubItems[4].BackColor = Color.Yellow;
}
else
{
itmX.SubItems[4].BackColor = Color.Green;
}
}
}
EventLog log = new EventLog(data_variables.RES_TXT_STRING_LOG_EVENT);
try
{
log.Source = data_variables.RES_TXT_STRING_LOG_SOURCE;
log.WriteEntry(data_variables.REX_TXT_STRING_MESSAGE_SUCCESSFUL, EventLogEntryType.Information);
}
if (listView_Selected_Index > -1)
{
//Keep the focus in the listview
this.listView1.Items[listView_Selected_Index].Focused = true;
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
now = DateTime.Now;
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
//Selecting the each values of the selected item from listview
listView_Selected_Index = listView1.SelectedIndices[i];
}
}
Can anyone help me how to remain the focus on the listview item even the refresh button is get clicked
You are removing original (some selected) items from the listview at the top of GetData().
You need to store somewhere what is selected before you read new data from database. Then after new data is displayed in listview you have to select items based on what was selected before data refresh.
//store selected items (id or sth else that identifies item)
GetData();
//restore selection (some of previously items may no longer exist)
In your code you only saving the last selected item not all of them.
for (int i = 0; i < listView1.SelectedItems.Count; i++)
{
//Selecting the each values of the selected item from listview
// here You are only saving last selected item
// instead of this do sth like
// selectedItems.Add(sth that identifies this item, not index)
listView_Selected_Index = listView1.SelectedIndices[i];
}
Also instead of doing it on every selectedIndexchanged You can do it only before data refresh unless you need it for some other reasons.
What you can do is, save the currently selected index of ListView1 in some temporary field and after calling GetData() method reset the selected index property of ListView1 by assigning value of temporary field to ListView1.SelectedIndex property
something like this:
private int _selectedIndex = -1;
private void btnRefresh_Click(object sender, EventArgs e)
{
_selectedIndex = listView1.SelectedIndex;
//to refresh manually
this.Refresh();
listView1.Items.Clear();
/*btnEdit_Question.Enabled = true;
btnRepeat_Question.Enabled = true;
btnDelete_Question.Enabled = true;*/
GetData();
listView1.SelectexIndex = _selectedIndex;
}