I'm beginner in programming.
I created an sql query to fill up a DataGridView and I added in the Column[0] a CheckBox column. I created the checking event. But I don't know how to step forward. I would like to do in
First step: add a check finished button and an event to show only the checked columns.
Second step: all the selected columns rows cell 1 (Name) and cell 2 (ID) to print somehow.
Third step: I want to create a template to print this name and id to an A4 format within rectangles or some object.
Because I'm new here I need a lot of help!
Thanks in advance!
ps: All step will be a big help for me!
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (string.Compare(dataGridView1.CurrentCell.OwningColumn.Name, "Checked") == 0)
{
bool checkBoxStatus = Convert.ToBoolean(dataGridView1.CurrentCell.EditedFormattedValue);
//"CheckBoxColumn" column value is checked or not.
if (checkBoxStatus)
{
MessageBox.Show("1");//for check it works or not
}
else
{
MessageBox.Show("0");//for check it works or not
}
}
}
To detect checked rows, when your first column is DataGridViewCheckBoxColumn you can use this code:
var checkedRows = this.dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => (bool?)row.Cells[0].Value == true)
.ToList();
For the rest of problem you can use either of these options:
Option 1: Create an RDLC Report
If you are using a DataTable or a business object as model of your grid, you can simply create an RDLC Report and pass checked rows to the report and print the report.
Option 2: Print using PrintDocument
To print, use a PrintDocument and handle PrintPage event and put the print logic and codes there. To trigger the print event, it's enough to call printDocument1.Print() somewhere in your code.
You can loop over checkedRows and use e.Graphics.DrawString to print values from each row.
For example:
private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
//Find all checked rows
var allCheckedRows = this.dataGridView1.Rows.Cast<DataGridViewRow>()
.Where(row => (bool?)row.Cells[0].Value == true)
.ToList();
//create a stringBuilder that will contain the string for all checked rows
var builder = new StringBuilder();
//For each checked row, create string presentation of row and add to output stringBuilder
allCheckedRows.ForEach(row =>
{
//Create an array of all cell value of a row to then concatenate them using a separator
var cellValues = row.Cells.Cast<DataGridViewCell>()
.Where(cell => cell.ColumnIndex > 0)
.Select(cell => string.Format("{0}", cell.Value))
.ToArray();
//Then concatenate values using ", " as separator, and added to output
builder.AppendLine(string.Join(", ", cellValues));
});
//Print the output string
e.Graphics.DrawString(builder.ToString(),
this.myDataGridView.Font,
new SolidBrush(this.dataGridView1.ForeColor),
new RectangleF(0, 0, this.printDocument1.DefaultPageSettings.PrintableArea.Width, this.printDocument1.DefaultPageSettings.PrintableArea.Height));
}
To add a button to DataGridView:
DataGridViewButtonColumn editButton = new DataGridViewButtonColumn();
editButton.HeaderText = "Edit";
editButton.Text = "Edit";
editButton.UseColumnTextForButtonValue = true;
editButton.Width = 80;
dbgViewObj.Columns.Add(editButton);
EDIT:
You could create a new DataTable from the previous one and iterate in a for loop to check the state of the checkbox and using the dgv.Rows.RemoveAt(index) method to clear the rows that are not checked.Then use dgv.Columns.Columns.Remove("column_name") to clear the checkbox column itself.
Related
I have a DatagridView which contains row and data. I've added checkboxs to select one of the row (1) and then generate a PDF with the data of the selected row (2) (see picture) :
My code contains a part which check if checkbox is 1 or 0 and then I don't know how to get the data of the "checked row".. See
private void button_generer_pdf_Click(object sender, EventArgs e)
{
List<DataGridViewRow> rows_with_checked_column = new List<DataGridViewRow>();
foreach (DataGridViewRow row in dataGrid_factures.Rows)
{
if (Convert.ToBoolean(row.Cells[column_action.Name].Value) == true)
{
MessageBox.Show("OK!"); // Just to check if it undestands I've checked the row
//And then here I want to get highlighted data on the screenshot to create my Pdf
}
}
//PDF Generation here
The same way you got the data from your selection column "row.Cells[column_action.Name].Value" by changing it to be the right name so maybe
row.Cells["NOM"].Value
or you can use the array number should you know it eg
rows.Cells[3].Value
hi my friend you can use this code for any cell or use a loop for all cells!!!
public void ReadDataFromDataGridView()
{
string value = dataGridView1.SelectedRows[0].Cells["columnName"].Value.ToString();
}
I have a DataGridViewfilled with information from my SQL:
[Its only possible to click one complete row and not only a cell, shown in my picture]
I try some Code example from: Reading data from DataGridView in C# but it dosent work for my Problem.
I try this, because it seems good
dataGridView.Rows[MyIndex].Cells["MessageHeadline"].Value.ToString();
but i get an Error.
Now i want to take the Index (add with 1, because its start with 0) and if i press on a row, my program should take the information from my DataGridViewand give it back.
Try to use CurrentRow instead of SelectedRow. The selected row only perform if you have selected row from RowHeader or the RowSelection property is set FullRowSelect. But, CurrentRow is actually focused row. You can get value even you have selected only single cell.
dataGridView.CurrentRow.Cells["MessageHeadline"].Value.ToString()
Try this:
Set the SelectionMode property of your datagridview to CellSelect. Now you will be able to select a cell itself.
And in CellMouseClick Event:
private void MyGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string FullContent = "";
for (int i = 0; i < MyGridView.Columns.Count; i++)
{
FullContent += MyGridView.Rows[e.RowIndex].Cells[i].Value.ToString() + "^";
}
FullContent = FullContent.Substring(0, Content.Length - 1);
string[] Content=FullContent.Split('^')
}
Now you can get each column content from Content array.
Like:
Content[0],Content[1],Content[2],etc.
For example, if you click the first row in your datagridview.
You can access the contents like:
FullContent; //1^Test BGW 1^Test^All^12.05.2014^.....
Splitted contents:
Content[0]; //1
Content[1]; //Test BGW 1
Content[2]; //Test
Content[3]; //All
Content[4]; //12.05.2014
just using the foreach loop can solve the problem.
foreach (DataGridViewRow row in gridStore.Rows)
{
MessageBox.Show(row.Cells[2].Value.ToString()); //row.Cell[index Here!]
}
I have a webpage with a gridview attached to it. The gridview allows the user to update individual records. The gridview looks like this:
JobSiteID JobSite1
1 13-03
2 13-04
3 13-06
4 13-09
5 13-15
I created the following record updating event handler:
protected void changeJobSiteRecordsGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = changeJobSiteRecordsGridView.Rows[e.RowIndex];
TextBox txtJobSite = row.FindControl("txtJobSite") as TextBox;
if (txtJobSite != null)
{
using (ABCEntities4 Context = new ABCEntities4())
{
int jobSiteID = Convert.ToInt32(changeJobSiteRecordsGridView.DataKeys[e.RowIndex].Value);
JobSite obj = Context.JobSites.First(x => x.JobSiteID == jobSiteID);
obj.JobSite1 = txtJobSite.Text;
Context.SaveChanges();
changeJobSiteRecordsGridView.EditIndex = -1;
changeJobSiteRecordsGridView.DataSource = Context.JobSites;
changeJobSiteRecordsGridView.DataBind();
}
}
}
Here's my problem:
When I select to update, say row #2, on the first line, the local "row" variable indicates that the RowIndex == 1.
However, in the second line, I expect txtJobSite variable to be populated with "13-04" but VS assigns "null" to the variable.
As a result, the code flows over the if then statement below which isn't what was intended.
Any help would be greatly appreciated.
Thanks.
Check the row's cells property like this:
row.Cells[1].Controls[0]
for the text box. If the '0' index doesn't work, try the 1 index. Then your code would look something like this:
TextBox txtJobSite = (TextBox)row.Cells[1].Controls[1]
I remember running into a similar problem with FindControl. This way, you explicitly find the cell and then the control in the cell.
I have a datagridview that contains list of subjects populated from Subject table from database.Columns include
Select(checkbox),
SubjectId,
SubjectName,
SubjectGroup.
Now I want if a user Selects on any of the desired rows, the corresponding SubjectId's should be added to a List. I have made and inserted into the desired table in the database.
The problem is that the new column of checkboxes I have added to this datagridview is not being detected.
My code is:
foreach (DataGridViewRow row in gvSubjectsOpted.Rows)
{
if (Convert.ToBoolean(gvSubjectsOpted.SelectedRows[0].Cells["SelectId"].Value=true))
{
olist.Add(gvSubjectsOpted.SelectedRows[0].Cells["SubjectId"].Value.ToString());
}
}
Late to the party. I had the same issue with trying to get the checkbox column by name, use the index instead. Here is a linq example assuming the checkbox is column 0 and the stored values for TrueValue and FalseVale are true and false respectively.
var checkedRows = from DataGridViewRow r in gvSubjectsOpted.Rows
where Convert.ToBoolean(r.Cells[0].Value) == true
select r;
foreach (var row in checkedRows)
{
olist.Add(row.Cells["SubjectId"].Value.ToString());
}
I realise this is an old post but I came across it and didn't think it was really answered in an efficient way so I thought I would add my method.
I have a similar block in my windows app. I read the values from the grid when the user clicks a button, and I want to know which rows they checked. As the checkboxes are in Cell 0 and the data I want is in Cell 1, I use the following code. Note the cast: it is important as it allows us the use the Where clause and therefore just a single line of code to get the collection of data. I could use the name of the cells instead of magic index numbers but then it would not fit your app so I put numbers instead (you should use names)
var checkedRows = dataGridView
.Rows
.Cast<DataGridViewRow>()
.Where(x => x.Cells[0].Value.ToString() == "1")
.Select(x => x.Cells[1]);
Note that this will give you an IEnumerable of type DataGridViewCell. If you want you can either add something like .Value.ToString() to the select or do this when you use your collection.
You question is similar to another SO question.
Check the answer of this Datagridview checkboxcolumn value and functionality.
Try this
foreach(GridViewRow r in gvSubjectsOpted.Rows)
{
GridViewCheckBoxColumn c = r.cells[0].Controls[0] as GridViewCheckBoxColumn;
if(c.Checked)
{
//Do something.
}
}
private void button1_Click(object sender, EventArgs e)
{
string subjId;
List<string> lines = new List<string>();
for (int i = 0; i < gvSubjectsList.Rows.Count; i++)
{
bool Ischecked =Convert.ToBoolean(gvSubjectsList.Rows[i].Cells["Select"].Value);
if (Ischecked == true)
{
subjId = gvSubjectsList.Rows[i].Cells["SubjectId"].Value.ToString();
lines.Add(subjId);
}
}
comboBox1.DataSource = lines;
}
//the most important thing is to set 'true' and 'false' values against newly added checkboxcolumn instead of '0' and '1'...that is,
CBColumn.FalseValue = "false";
CBColumn.TrueValue = "true";
I want to make a search list using datagridview in c#. I have a text box where one can enter the customer name. When the "search" button is clicked, i will hide all the rows where the CustomerName is not equal to the searchValue.
The problem is that when the user want to search for the second time, how can I search through the hidden rows of the dgv. Do i need to make visible the rows hidden.
Thanks.
Here is the Code.
private void search_Click(object sender, EventArgs e)
{
arrayList= new ArrayList();
String searchValue = searchBox.Text;
for (int i = 0; i < dataGridView1.RowCount-1; i++)
{
if ( (dataGridView1.Rows[i].Cells[1].Value.ToString().Trim() ).Equals (searchValue.Trim()) )
{
//dataGridView1.Visible = true;
arrayList.Add(i);
}
else
{
dataGridView1.Visible = false;
}
}
dataGridView1.Refresh();
}
Are you using a datatable to bind the datagridview?
If you are, when you are searching you could iterate the datatable and delete the rows that do not match your search criteria. When you search you can rejectchanges on your datatable to have the original data again. Afterwards you can use the same process that was used in the first place (mark the datarows that do not match the search criteria as deleted).
Another alternative can be using a DataRowView and filter with your search criteria and use the that datarowview to bind the datagridview. I would prefer this last one.