Adding Image column based DataGridViewCheckBoxCell - c#

This is what I have coded:
private void DeleteButton_Click(object sender, EventArgs e)
{
//Add column for status
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn.Name = "ImageColumn";
imageColumn.HeaderText = "Status";
FilesDataGridView.Columns.Add(imageColumn);
FilesDataGridView.Columns[2].Width = 45;
foreach (DataGridViewRow dr in FilesDataGridView.Rows)
{
DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dr.Cells["ChkColumn"];
DataGridViewImageCell cell = dr.Cells[2] as DataGridViewImageCell;
if (checkCell.Selected == true)
{
//need code to display the Image for this column here..
}
else
{
//need code to display the Image for this column here..
}
}
}

Related

How to format a specific item in the ComboBox in a DataGridViewComboBoxColumn?

I have code similar to this in a method that (re)creates the columns in the DataGridView:
MyColumn = new DataGridViewComboBoxColumn()
{
Name = "..",
HeaderText = "..",
SortMode = DataGridViewColumnSortMode.NotSortable
};
MyColumn.Items.Clear();
foreach (string s in MyStringList)
{
MyColumn.Items.Add(s);
}
MyColumn.Items.Add("");
// I would like this empty string to be shown as "No group"
// with an italic grayed out font
I think that I probably must create a class for the items of the ComboBox-es in the column, in which I should override the ToString() method, but I want to know how to format the No Group item.
A related question is here which is a about a normal ComboBox not inside a DataGridView, with the answer solving the problem using the DrawMode prperty and DrawItem event of the ComboBox class.
For custom-painting the ComboBox, you need to handle EditingControlShowing and then get the EditingControl which is DataGridViewComboBoxEditingControl and then set its DrawMode to OwnerDrawFixed and handle its DrawItem event.
For custom-painting the cell, you need to handle CellPainting event and set different font and color for the cell styles and let the paint continue with new values. You can also paint the whole cell if you want.
Example
Load Sample Data:
private DataTable LoadProducts()
{
var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("CategoryId", typeof(int));
dt.Rows.Add("P1", 1);
dt.Rows.Add("P2", 1);
dt.Rows.Add("P3", DBNull.Value);
return dt;
}
private DataTable LoadCategories()
{
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name");
dt.Rows.Add(DBNull.Value, "No Category");
dt.Rows.Add(1, "C1");
dt.Rows.Add(2, "C2");
dt.Rows.Add(2, "C3");
return dt;
}
Setup DataGridView Columnms:
private void Form1_Load(object sender, EventArgs e)
{
var products = LoadProducts();
var categories = LoadCategories();
dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()
{
Name = "NameColumn",
DataPropertyName = "Name",
HeaderText = "Name"
});
dataGridView1.Columns.Add(new DataGridViewComboBoxColumn()
{
Name = "CategoryIdColumn",
DataPropertyName = "CategoryId",
HeaderText = "Category",
DataSource = categories,
ValueMember = "Id",
DisplayMember = "Name",
DisplayStyle= DataGridViewComboBoxDisplayStyle.Nothing
});
dataGridView1.DataSource = products;
dataGridView1.EditingControlShowing += DataGridView1_EditingControlShowing;
dataGridView1.CellPainting += DataGridView1_CellPainting;
}
Handle EditingControlShowing
private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1?.CurrentCell?.OwningColumn?.Name != "CategoryIdColumn")
return;
var combo = e.Control as DataGridViewComboBoxEditingControl;
if (combo == null)
return;
combo.DrawMode = DrawMode.OwnerDrawFixed;
combo.DrawItem += (obj, args) =>
{
var txt = args.Index >= 0 ? combo.GetItemText(combo.Items[args.Index]) : "";
var textColor = args.Index == 0 ? SystemColors.GrayText : SystemColors.ControlText;
var font = args.Index == 0 ? new Font(combo.Font, FontStyle.Italic) : combo.Font;
if ((args.State & DrawItemState.Selected) == DrawItemState.Selected)
{
textColor = SystemColors.HighlightText;
}
args.DrawBackground();
TextRenderer.DrawText(args.Graphics, txt, font,
args.Bounds, textColor,
TextFormatFlags.VerticalCenter | TextFormatFlags.Left);
};
}
Handle CellPainting
private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0 ||
dataGridView1.Columns[e.ColumnIndex].Name != "CategoryIdColumn")
return;
if (dataGridView1[e.ColumnIndex, e.RowIndex].Value == DBNull.Value)
{
e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Italic);
e.CellStyle.ForeColor = SystemColors.GrayText;
}
else
{
e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Regular);
e.CellStyle.ForeColor = SystemColors.ControlText;
}
}

AutocompleteSource in datagridviewtextBoxColumn

I'm trying to add AutoCompleteSource in datagridViewtextBoxColumn. I'm trying two methods.In the first one i'm directly adding AutoCompleteSource to datagridViewColumn. And in the second i created a textBox on the desired cell and added AutocompleteCustome Source. But none of this working with no exception.
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
DataGridViewCell cel = dataGridView1.CurrentCell;
DataGridViewRow row = dataGridView1.CurrentRow;
if (e.Control.GetType() == typeof(DataGridViewTextBoxEditingControl))
{
if (cel == row.Cells[1])
{
DataGridViewTextBoxEditingControl t = e.Control as DataGridViewTextBoxEditingControl;
AutoCompleteStringCollection ccl = new AutoCompleteStringCollection();
foreach (DataRow rw in bowoniDataSet17.item.Rows)
{
ccl.Add(rw.ToString());
}
t.AutoCompleteSource = AutoCompleteSource.CustomSource;
t.AutoCompleteCustomSource = ccl;
t.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
}
}
}
TextBox tb = new TextBox();
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
DataGridViewRow row = dataGridView1.CurrentRow;
DataGridViewCell cel = dataGridView1.CurrentCell;
Rectangle rect=dataGridView1.GetCellDisplayRectangle(dataGridView1.CurrentCell.ColumnIndex,dataGridView1.CurrentCell.RowIndex,true);
tb.Size = new Size(rect.Width, rect.Height);
tb.Location = new Point(rect.X, rect.Y);
tb.TextAlignChanged += new EventHandler(tbtx_OnTextChanged);
if (cel == row.Cells[1])
{
AutoCompleteStringCollection ccl = new AutoCompleteStringCollection();
foreach (DataRow rw in bowoniDataSet17.item.Rows)
{
ccl.Add(rw.ToString());
}
tb.AutoCompleteSource = AutoCompleteSource.CustomSource;
tb.AutoCompleteCustomSource = ccl;
tb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
}
}
private void tbtx_OnTextChanged(object sender, EventArgs e)
{
dataGridView1.CurrentCell.Value = tb.Text;
}
Now i changed it to DataGridViewComboxColumn.Working fine.

How can I update a text file when I move from gridview to textbox

I read text to the GridView and then move this text from the GridView to TextBoxes to edit. How can I replace the changed data from selection line and save to my text file?
this is my write file
private void button1_Click(object sender, EventArgs e)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"WriteLines2.txt", true))
{
file.WriteLine(this.id.Text + "#" + this.judul.Text + "#" + this.isi.Text);
}
}
this is my gridview
System.IO.StreamReader file = new System.IO.StreamReader("WriteLines2.txt");
string[] columnnames = file.ReadLine().Split('#');
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
dt.Columns.Add(c);
}
string newline;
while ((newline = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split('#');
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i];
}
dt.Rows.Add(dr);
}
file.Close();
GridView.DataSource = dt;
this is my grid view move to textbox
private void GridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridViewRow dr = GridView.SelectedRows[0];
id.Text = dr.Cells["id"].Value.ToString();
// or simply use column name instead of index
//dr.Cells["id"].Value.ToString();
judul.Text = dr.Cells["judul"].Value.ToString();
isi.Text = dr.Cells["subjek"].Value.ToString();
//textBox4.Text = dr.Cells[3].Value.ToString();
GridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
You should call the GridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; when you initialize your DataGridView and not during the CellContentClick. Then use the SelectionChanged Event instead of the CellContentClick Event and use CurrentCell.RowIndex for the index:
private void GridView_SelectionChanged(object sender, EventArgs e)
{
DataGridViewRow dr = GridView.Rows[GridView.CurrentCell.RowIndex];
id.Text = dr.Cells[0].Value.ToString();
judul.Text = dr.Cells[1].Value.ToString();
isi.Text = dr.Cells[2].Value.ToString();
}
Your buton1_Click adds a new values to the end of your file. I'm not sure if that is what you want.

how to store multiple values of checkbox values in viewstate?

here is the code for my viewstate. but it's only store one value.what i need is it will keep the selected multiple values in the checkbox. this method is to keep/hold the value of check box in gridview of paging situation.
public void chkAssignee_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox selectBox = (CheckBox)sender;
GridViewRow myRow = (GridViewRow)selectBox.Parent.Parent; // the row
GridView myGrid = (GridView)myRow.Parent.Parent; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString();
GridViewRow rowSelect = (GridViewRow)selectBox.Parent.Parent;
int a = rowSelect.RowIndex;
ViewState["id"] = ID;
}
Try Following
Following Code may help u.
public void chkAssignee_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox selectBox = (CheckBox)sender;
GridViewRow myRow = (GridViewRow)selectBox.Parent.Parent; // the row
GridView myGrid = (GridView)myRow.Parent.Parent; // the gridview
string ID = myGrid.DataKeys[myRow.RowIndex].Value.ToString();
GridViewRow rowSelect = (GridViewRow)selectBox.Parent.Parent;
int a = rowSelect.RowIndex;
ArrayList SelecterdRowIndices=new ArrayList();
if(ViewState["SelectedRowIndices"]!=null)
{
SelecterdRowIndices=(ArrayList)ViewState["SelectedRowIndices"];
bool flag=false;
foreach (int i in SelecterdRowIndices)
{
if(i==Convert.ToInt32(ID))
{
flag=true;
break;
}
}
if(!flag)
{
SelecterdRowIndices.Add(ID);
}
}
else
{
SelecterdRowIndices.Add(ID);
}
ViewState["SelectedRowIndices"] = SelecterdRowIndices;
}

gridview programming using c sharp

How can i get multiple selected rows in gridview using c# code & that selected rows i have to display in another form which also have gridview
public partial class WindowForm: Form
{
private DataTable dataTable = new DataTable();
//This will contain all the selected rows.
private List<DataGridViewRow> selectedRows = new List<DataGridViewRow>();
public WindowForm()
{
InitializeComponent();
dataTable .Columns.Add("Column1");
dataTable .Columns.Add("Column2");
dataTable .Columns.Add("Column3");
for (int i = 0; i < 30; i++)
{
dataTable .Rows.Add(i, "Row" + i.ToString(), "Item" + i.ToString());
}
dataGridView1.DataSource = dataTable ;
//This will select full row of a grid
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//This will allow multi selection
dataGridView1.MultiSelect = true;
dataGridView1.CurrentCellChanged += new EventHandler(dataGridView1_CurrentCellChanged);
dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
}
void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
PerformSelection(dataGridView1, selectedRows);
}
void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
{
if (selectedRows.Contains(dataGridView1.CurrentRow))
{
selectedRows.Remove(dataGridView1.CurrentRow);
}
else
{
selectedRows.Add(dataGridView1.CurrentRow);
}
PerformSelection(this.dataGridView1, selectedRows);
}
private void PerformSelection(DataGridView dgv, List<DataGridViewRow> selectedRowsCollection)
{
foreach (DataGridViewRow dgvRow in dgv.Rows)
{
if (selectedRowsCollection.Contains(dgvRow))
{
dgvRow.Selected = true;
}
else
{
dgvRow.Selected = false;
}
}
}
}

Categories

Resources