Menu
  • HOME
  • TAGS

Object reference not set to an instance of an object on retrieving text from datagridview

datagridview,vb.net-2010

Do it like; For Each row As DataGridViewRow In EmployeesDataGridView.rows For Each cell As DataGridViewCell In row.cells If cell.Value.ToString.ToUpper.Contains(someText.ToUpper) Then cell.Style.BackColor = Color.Yellow End If Next Next Hope it helps...!!!...

C# - Creating 2 dimensional array from multiple datagridviews

c#,arrays,datagridview

Since you have said you have 7 data grid views and that each has dimensions 7 x 5 I have removed some of the loop constraints and replaced them with constants. I wouldn't normally recommend that, but since you are using 2 dimensional arrays and you've specified the values it...

How to add empty value from gridview cell to list?

c#,linq,list,datagridview,datagridviewtextboxcell

Your problem is that your cell values can be string, DBNull.Value or null. null.ToString() throws the object reference not set to instance of an object exception. To avoid that you can first set your object as string to get rid of the DBNull.Value and then use the null-coalescing operator to...

RowLeave event called when DataGridView loads

vb.net,datagridview,row

As your DataGridView is populated with the rows, the rows are sure left programmatically if the DataGridView looses the focus. To avoid your code will fire when the form is loading the rows to the DataGridView, I could think of two solutions. Only execute the logic in your GradeGridView_RowLeave()-method Me.IsLoaded()...

Crystal Reports only shows the last column

vb.net,datagridview,crystal-reports

The column titles in Database and Dataset has to be the same. Also, using Select Column1, Column2, ColumnN ... is always the better way than writing just Select * in query. Titles should/can be edited in Report file, which will change the showing title of that column, of course the...

How can i make excel like grid in asp.net C# Webform

asp.net,gridview,datagridview,webforms

Hope this will help you out to full-fill your requirement.Here I am giving only aspx and c# coding. Create and modify your database and change the code accordingly.Here I am using direct insert statement you can use stored procedure. Table in Database:- page.aspx :- <asp:GridView ID="excelgrd" runat="server" AutoGenerateColumns="false" ShowFooter="true"> <Columns>...

Binding Source NOT reflecting new/removed Row when List datasource adds/removes item

c#,datagridview,bindingsource,bindinglist

OK , finally have found a solution to my problem. Mahmoud thanks for the suggestion but I ended up having the same issue. Somewhere in my code I think something (I don't know exactly what) was getting lost when I made the reference from the main list to the binding...

Datagridview doesnt auto select first row after filling datasource

vb.net,visual-studio-2010,data-binding,datagridview

you're currently checking if there are any rows but not any selected rows: Public Sub refreshDT() Dim cnt As Integer = DGV_SalMaliDataGridView.Rows.Count If cnt = 0 Then lockAll() Exit Sub End If If DGV_SalMaliDataGridView.SelectedRows.Count = 0 Then DGV_SalMaliDataGridView.Rows(0).Selected = true End If unlockAll() Dim sel As String = DGV_SalMaliDataGridView.SelectedRows(0).Cells(1).Value Dim...

Saving Data To DataSet That Has Been Set Up Programmatically

vb.net,datagridview,dataset

I Finally resolved the question with the following code, placed inside the Save button: Public Sub Save() Dim myCon = New OleDbConnection(My.Settings.Database_String) myCon.Open() Dim sqr = "UPDATE [Spares] SET [Name Of Person] = """ & Main.VIEW_NameOfPerson.Text & """, [SAP Job Number] = " & CInt(Main.VIEW_SAPJobNo.Text) & ", " & _...

How to unhighlight row in dataviewgrid C#

c#,datagridview,datatable

You can use dataGridView1.ClearSelection(); Or dataGridView1.CurrentCell = Nothing; Or dataGridView1.Rows[Index].Selected = false; ...

Draw image in the DataGridView header by text's side

c#,image,winforms,datagridview

You can use something like this for a DataGridView DGV: private void DGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.ColumnIndex == yourColumn && e.RowIndex == -1) { DGV.ColumnHeadersHeight = 32; // or maybe a little more.. // should be prepared, maybe in an imagelist!! Image img = Image.FromFile("D:\\dollars96.png"); Rectangle r32 =...

Adding contents of a DataViewGrid to access - VB

vb.net,gridview,datagridview

You keep adding parameters over and over. Try clearing them at the beginning of the loop: For x As Integer = 1 To DataGridView1.Rows.Count - 1 cmd.Parameters.Clear() and avoid empty Try-Catches. You are ignoring problems in your code when you do that. For one thing, the "Age" field probably shouldn't...

Get Selected Row in DataGridView not working VB.Net

vb.net,datagridview,selectedindex

I think what you are looking for is DataGridView CellClick instead of CellContentClick. CellContentClick does not fire when white space around the cell content is clicked. Private Sub DataGridView2_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView2.CellClick Try If e.RowIndex >= 0 Then Dim row As DataGridViewRow row =...

VB.NET XtraGrid Change cell color after its value is edited

.net,vb.net,datagridview,devexpress

I finally managed to do it in the following way! you need to handle two events: GridView.CellValueChanged GridView.CustomDrawCell You need to keep track of every changed cell's indices. So, we need a List Create a class and three fields in it. Public Class UpdatedCell 'UC means UpdatedCll Public Property UCFocusedRow...

Showing Database Search results in Datagridview

c#,sql-server,winforms,visual-studio-2013,datagridview

When you put your connection in a USING it will automatically close and dispose your connection when the block exits. public void customerSearch(int custID, DataGridView dataGridView) { using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString)) { try { connection.Open(); SqlCommand searchQuery = new SqlCommand("select * from [Customer] where custId = @custID", connection);...

visually select datagridview cell

c#,datagridview

Before controls are displayed you cannot set focus to them. Event handler of Shown event is good place for this. This event raised only once when form displayed first time (MSDN Form.Shown Event). You only need save tags values from tagList in the variable for later using in the Shown...

Search for a column in database table and add the values to a datagridview

database,vb.net,datagridview

Change your code as this... you should add columns in-order to add rows as u expect Dim table As DataTable = myTable.Tables("fruits") Dim expression As String expression = "item = 'apple'" Dim foundRows() As DataRow foundRows = table.Select(expression) Dim col, col1, col2 As New DataGridViewTextBoxColumn col.HeaderText = "ID" col1.HeaderText =...

Operator '-' is not defined for type 'Double' and type 'DBNull'. [vb.net datagridview]

datagridview,vb.net-2010

The message means that in this code: Me.grdPurchase.Rows(Me.grdPurchase.CurrentCell.RowIndex).Cells("grossamt").Value - _ Me.grdPurchase.Rows(Me.grdPurchase.CurrentCell.RowIndex).Cells("discamt").Value One of the 2 cells is DBNull. Based on the message, it is a cell involved in subtraction, which is these 2. The odd thing is that else where you are testing cell after cell for DBNull, but not...

Display value from datagridview to textbox in other form c#.Net

c#,vb.net,winforms,datagridview,textbox

It's been a while since I used Winforms, but personally I would use events: bind the appropriate DataGridView event (in this case CellClick is probably most relevant) to a method that lives inside Derogatory Form. From that method you should be able to access the event information, which should allow...

Populate DataGridView Column With a Double forcing to 2 Decimal Places, with Sort

vb.net,sorting,datagridview,formatting

You are converting your values to string by using the legacy VB Format function: Function Format(Expression As Object, Optional Style As String = "") As String When it is converted, the other decimals are lost. Use the Format Property of the DefaultCellStyle for that column to specify the number of...

DataGridView value doesn't change when calling CellContentClicked event

c#,datagridview

great answer by taw, thanks for your help. Your answer is wrong because i already used the method that u asked me to use, but the result is still same. In the end, i realize what wrong with it is because when i tick the check box, the column itself...

DropDown in datagridView

c#,visual-studio-2013,datagridview,combobox,ssms

thank you! i found the answer public Form1() { InitializeComponent(); load_input_table(); load_output_table(); dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing); } static String conn = @"Data Source=SUMEET-PC\MSSQLSERVER1;Initial Catalog=EMIDS;Integrated Security=True"; SqlConnection connection = new SqlConnection(conn); DataGridViewComboBoxColumn inputtablecombobox = new DataGridViewComboBoxColumn(); private void load_input_table() { String sql = "select * from...

Selecting different connection strings for data gridview

vb.net,datagridview,sqldataadapter

First, I don't see you open your connection. Then, you got it a bit up side down... Using con As New SqlConnection(LogConnectionString) con.Open() Using cmd As New SqlCommand("dbo.getLogMessages", con) cmd.CommandType = CommandType.StoredProcedure Using da As New SqlDataAdapter(cmd) ' We need to clear out old data before reloading if same DS...

System.DBNull Error on formatting DataGridView C#

c#,.net,datagridview

DBNull.Value is of type DBNull and cannot be cast to a string. Instead, use Convert.ToString to handle this case. Demo Also, for what it's worth, DBNull.Value is not the same as null. See this answer for details....

Last checked row in datagridview checkbox column is not checked

c#,datagridview,datagridviewcheckboxcell

OK, I found what cause this behavior. Last checked checkbox is still in edit mode when i'm getting his value with (bool)dgvInputFile.Rows[currentRow].Cells["boolCol"].FormattedValue Insted i should use DataGridViewCell.EditedFormattedValue property. MSDN Gets the current, formatted value of the cell, regardless of whether the cell is in edit mode and the value has...

Visual Basic Datagrid View change row colour

vb.net,datagridview,datagrid

Is it possible that your datagridview isn't loaded fully when you try to recolor the rows? Since you are setting the datasource, you should put your code that affects the grid after you can make sure that it is finished loading. The column widths change because it is not dependent...

export datagridview header column to excel vb 2012

vb.net,excel,datagridview

I think you'll have to get the HeaderText from each column like this: xlSheet.Cells(x,y).Value = DataGridView1.Columns(k).HeaderText You would put this in your "k" loop. And then write it wherever you want in the file. x and y have to be the location where you write the header (maybe determined by...

Get Selected index and Selected item from DataGridViewComboBoxCell in unbound column

c#,.net,winforms,datagridview

Given the CustomItem class, with the Value as an int public class CustomItem { public string Text { get; set; } public int Value { get; set; } public override string ToString() { return Text; } public CustomItem(string text, int value) { this.Text = text; this.Value = value; } }...

DataGridView KeyDown manipulation (enter, left, right, etc.) not working when multiselect

c#,winforms,datagridview,multi-select

In your GridNavigation method, under both conditions, if (keys == Keys.Enter || keys == Keys.Right) and else if (keys == Keys.Left), the guilty party here is the recurring line: dataGridView1.Rows[iRow].Cells[i].Selected = true; What went wrong? When dataGridView1.MultiSelect == false the above line effectively sets the current cell, not just the...

Entity Framework Datagridview delete strange behaviour

c#,winforms,entity-framework,datagridview

By default, when you hit the delete key when a DataGridView is focused, it removes the row from the DataGridView and from the bound collection. However, you're handling the KeyDown event yourself, removing the row, and updating DGUser.DataSource before the default action even occurs. Here's the order of actions (I...

Windows Form: change dataGridView's first cell origin?

c#,winforms,matrix,datagridview

Create one class like this: public class MyDataGridView : DataGridView { public new DataGridViewCell this[int col, int invertRow] { get { int recordCount = this.RowCount - (this.AllowUserToAddRows ? 2 : 1); return this.Rows[recordCount - invertRow].Cells[col]; } set { int recordCount = this.RowCount - (this.AllowUserToAddRows ? 2 : 1); this.Rows[recordCount -...

Generate sheet separated excel with GridView in MVC web enviroment

c#,asp.net,asp.net-mvc,excel,datagridview

I would use something like OpenXML. I'm guess the reason your creating the excel file on the fly is because you don't want to use interop objects because they are too heavy and bulky. However you still need the flexibility to manipulate objects. I would look at the OpenXML library...

Insert column with different values after binding DataGridView

datagridview,cell

for (int i = 0; i < dgvPersonnelInfo.Rows.Count; i++) { dgvPersonnelInfo.Rows[i].Cells[4].Value = arabicDeathYearMonth; } I assume you are performing the above code in the Form constructor; that was the only way I could replicate your empty column. Move this code somewhere else, say Form.Load. This should solve the main...

XmlReader DataGridView flip column and rows

xml,vb.net,datagridview

My final code (working): Public Function FlipDataSet(my_DataSet As DataSet) As DataSet Dim ds As New DataSet() For Each dt As DataTable In my_DataSet.Tables Dim table As New DataTable() table.Columns.Add(New DataColumn("f")) table.Columns.Add(New DataColumn("v")) Dim r As DataRow For k As Integer = 0 To dt.Columns.Count - 1 r = table.NewRow() r(0)...

Filling DataGridView row by row only populates last row

vb.net,excel,datagridview,oledb

I'm pretty sure your datagridview has the AllowUserToAddRows property set to True. If so, every time you use DataGridView2.Rows.Add(), that row is added before the last one; that's because the last row is the one the user uses to manually add a row to your grid. But in your loop...

Image Displaying a Red “X” in a DataGridView when loading from Resources

c#,image,datagridview

What you have will work for rows that are added via DataGridView.DataSource. However, as you've seen, the NewRow still displays a red x. This could be solved as shown here. However, once you've edited a cell of the NewRow and another one is added, the editing row no longer has...

Handling concurrency exceptions in DataGridView

c#,vb.net,winforms,datagridview,dataset

The solution turned out to be pretty simple. All you need to do is reload the data into the DataGridView again after every save. So the code for the BindingNavigator save button is now: this.Validate(); this.maintableBindingSource.EndEdit(); this.tableAdapterManager.UpdateAll(this.yourDataSet); this.maintableTableAdapter.Fill(this.yourDataSet.yourtable); I have no idea why this works, so I need an expert...

Fill two datagridviews from one tableadapter

vb.net,datagridview,dataadapter

Is it possible? Of course, that's the glory of bound datasets. Set up your 2 queries using the DataSet designer (.xsd) by right-clicking on your TableAdapter-->Add Query --> etc. With two DataGridViews, you will need 2 instances of the same tableadapter (you can drag and drop from the Toolbox). Call...

C# Validate DataSet filled with DGV data as XML

c#,xml,validation,datagridview,xsd

If the question is why can't the file be deleted, it is because the XmlReader has the file open - call read.Close() before trying to delete the file.

XmlReader.Name returns an empty value

c#,datagridview

Say you had an XML structured like: <element>Some Text</element> First an XmlReader would first hit a node with type XmlNodeType.Element the name element, and an empty Value. Then it would hit a node with type XmlNodeType.Text, no name, and the value "Some Text". Then it would hit a node with...

Wrong row gets deleted in DataGridView bound to DataAdapter

c#,mysql,datagridview,delete-row,dataadapter

Ok generating the SQL Delete command doesn't work when I reference CurrentRow from the dgv because by the time I'm building my parameters and doing the adapter.Update that dgv row has gone. That's why I end up deleting the wrong row. So I've solved it like this: In the UserDeletingRow...

How to store multiple records in SQL Server using DataGridView

c#,sql-server,datagridview

The problem is within this " for " loop, you are not using the i in your for loop. better try this one. for (int i = 0; i < dataGridView1.Rows.Count; i++) { string col1 = dataGridView1.Rows[i].Cells[0].Value.ToString(); string col2 = dataGridView1.Rows[i].Cells[1].Value.ToString(); string col3 = dataGridView1.Rows[i].Cells[2].Value.ToString(); string insert_sql = "INSERT INTO...

Cancel some keyboard events on a control

c#,.net,datagridview,event-handling

I am not sure if I understand your question correctly. But if I am not wrong all you need is just "Handled" property on the KeyEventArgs object. When in your event handler you set that property to "true" no further processing for that particular event will be called: public void...

Inserting all the rows in a List View to a Data Grid View

vb.net,listview,datagridview

use While (num < ListView1.Items.Count) in place of While (num <= ListView1.Items.Count)

Set column visibility (properties) of added datagridview prior to adding the control to the form

vb.net,winforms,datagridview

Because columns are autogenerated they will be added after .DataSource is set. Add DataBindingComplete event handler where you can hide/remove columns With newGrid .Name = "dg" & r("tankShortCode").ToString .DataSource = newDataview AddHandler .DataBindingComplete, AddressOf Me.DataGridView_DataBindingComplete End With Create Event handler Private Sub DataGridView_DataBindingComplete(sender As Object, e AsDataGridViewBindingCompleteEventArgs) Dim dgv As...

Accessing a Combobox inside a dataGridView Column?

c++,datagridview,visual-c++-2010,datagridviewcombobox

Solution If you have access to the data from the user entry and you know the column index for the DataGridViewComboBoxColumn, you should be able to just do the following wherever needed: DataGridViewComboBoxColumn^ comboboxColumn = dataGridView->Columns[the_combobox_column_index]; if (comboboxColumn != nullptr) { comboboxColumn->Items->Add("the new user entry"); } Comments Response how could...

dataview.rowfilter syntax error - missing operand mystery

vb.net,datagridview,datatable,dataview,rowfilter

It looks like you have a white space in the Datatable column header. So, you have to enclose the Column name in the RowFilter within square brackets. Dim dtdv As New DataView dtdv = dt.DefaultView dtdv.RowFilter = "[Controller ID] = 'PS2USB1'" XMLDGV.DataSource = dtdv ...

Unable to bind data to DataGridView by using BindingList in WinForm application

c#,excel,winforms,datagridview

See this question: How to bind a List<string> to a DataGridView control? In your case you are using a BindingList<string> but the logic is the same. The DataGridView is looking for object properties to bind, String however, only has the property length....

How to write a T-SQL Stored Procedure to return data from three database tables

c#,sql-server,stored-procedures,datagridview

This is very basic SQL. I recommend you to read an sql tutorial. What you need is called a JOIN. Try this: SELECT [Name], [Title] FROM Book INNER JOIN BookAuthor ON(Book.Book_Id = BookAuthor.Book_Id) INNER JOIN Author ON(BookAuthor.Author_Id = Author.Author_Id) Also, for future questions, Please describe your tables as using DDL...

Validation DataGridView Windows Forms

c#,winforms,entity-framework,validation,datagridview

The answer is to add this.CausesValidation = false to the event handlers that are being triggered.

DataSet using first row as column header move the checkbox column 1 row down

c#,datagridview,dataset

unexpected checkbox in the last row of grid can be a result of DataGridView.AllowUserToAddRows property set to true (default), which adds new row for input try set AllowUserToAddRows to false for dgvInputFile by the way, when AllowUserToAddRows = true, the count of rows in grid (dgvInputFile.RowCount) is equal to dataset.Rows.Count...

Updating a list of objects bound to a DataGridView from a popup form

c#,winforms,datagridview

If the databound item does not contain notify property changed events, the user interface (datagridview) won't know anything has changed. You'll have to trigger the refresh manually. Either the entire grid or source or something like dataGridBasket.InvalidateRow(row.Index)

Improve DataGridView rows managing

.net,vb.net,winforms,datagridview,datatable

what can I do to manage a DataSource instead of directlly manage the rows collection of the control A Class and a collection are pretty easy to implement as a DataSource and will also it will be pretty easy to modify your MoveUp/Dn methods for it. Class DGVItem Public Property...

Merge DataGridView Image cell with text cell

c#,vb.net,image,winforms,datagridview

In its simplest form you could code the CellPainting event like this: private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.RowIndex < 0) return; // no image in the header if (e.ColumnIndex == yourImageColumn ) { e.PaintBackground(e.ClipBounds, false); // no highlighting e.PaintContent(e.ClipBounds); // calculate the location of your text..: int...

How to set a data grid column to be a drop down when binding to a table

vb.net,datagridview,datagridviewcolumn,datagridviewcomboboxcell

If the combobox column is going to have fixed values, you can manually define those values either at design time or at runtime (althought both ways require you to set AutoGenerateColumns property to False before you bind your data to your grid). If you want to do it by code,...

Newtonsoft Json Deserlize as C# Datagridview

c#,json,datagridview,json.net

The JSON is an array, not an object, so deserialize it as a DataTable: var dataTable = JsonConvert.DeserializeObject<DataTable>(json); Then add the DataTable to the DataGridView using this answer: Moving data from datatable to datagridview in C#....

Not getting values from grid table when checkbox is checked?

c#,winforms,datagridview,datagridviewcheckboxcell

Having a check-box column in your grid will not change the internal status of any of the rows, so you will need to iterate over them all yourself to evaluate. This should do the trick, although you will need to provide the correct column index for the checkbox column in...

Getting data from selected dataGridView to string

c#,datagridview

Try this way. Make sure change the property Multiselect = false and SelectionMode = FullRowSelect to ensure gets only one selection. SelectedRows.Count is always 0 until you select one if ( dataGridView1.SelectedRows.Count > 0) { string itemid = dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); string name = dataGridView1.SelectedRows[0].Cells[1].Value.ToString(); string description = dataGridView1.SelectedRows[0].Cells[2].Value.ToString(); } ...

DataGridView getting the background colour

c#,datagridview

It depends on the method you used to set the background color. If you have used something like: grid.Rows[r].DefaultCellStyle.BackColor = Color.Pink; you can only get the color value from that DefaultCellStyle, and your cell.Style.BackColor will be empty and returns RGB(0,0,0) or black. So you need to change your code to:...

Split comma separated strings 5 [closed]

c#,windows,datagridview,textbox

You do not need Split here, Just replace the comma in the string, string.Replace str = str.Replace(",", " "); Edit string []arr = str.Split('c'); txt1.Text = arr[0]; txt2.Text = arr[1]; txt3.Text = arr[2]; txt4.Text = arr[3]; txt5.Text = arr[4]; ...

Remove last row from DataGridView row count

c#,visual-studio,datagridview,foreach,rowcount

I fixed it by setting VRFileDataGrid.AllowUserToAddRows = false; before the loop and setting VRFileDataGrid.AllowUserToAddRows = true; after the loop. Probably not the best solution, but i works fine....

Two datagridviews bound to the same table. Refresh not working

c#,mysql,datagridview,refresh,dataadapter

It turned out that inserts and amendments were being reflected when I moved between tabs but not deletes. It then dawned on me that my (re)fill of the adapter would refresh amended rows and add new rows but it would leave removed rows untouched. So I simply inserted a DataTable.Clear...

Save Calculated Value from Spawned Child Form to Parent After Button Click

c#,forms,winforms,datagridview

As I understand If you want transfer value of calculated result from DeliveryLocationCalculator form to the main form and then close DeliveryLocationCalculator form, then create public property in DeliveryLocationCalculator for saving result, class DeliveryLocationCalculator { //... public decimal FinalResult { get; set; } } And use .ShowDialog() method for open...

Comparing DataGridView values

c#,winforms,datagridview

Use the RowEnter event: private void DataGridView1_RowEnter(object sender,DataGridViewCellEventArgs e) { btnUpdate.Enabled=!DataGridView1.Rows[e.RowIndex].Cells[10].Value.ToString().Equals("Completed") ; } Perhaps, the following is required just after having filled the gridview (I don't remember if the RowEnter event is raised or not at initialisation). btnUpdate.Enabled=DataGridView1.CurrentRow!=null && !DataGridView1.CurrentRow.Cells[10].Value.ToString().Equals("Completed") ...

DataGridView Cell value not available for validation when inserting a new row

c#,validation,datagridview

As the data are not yet validated they can't be in the Cell's Value field. Instead the input, as entered by the user, is both in the EditedFormattedValue field of the Cell..: dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].EditedFormattedValue ..and the FormattedValue field of the parameter e..: e.FormattedValue Note that both are of type object, already,...

changing the order of records in dataset

c#,winforms,datagridview,dataset

Try below things : var temp = dsWinners.Tables[0].Rows[index]; \\getting row var newrow = dsWinners.Tables[0].NewRow(); \\ creating new row to insert newrow.ItemArray = temp.ItemArray; \\ copying data from old to new row dsWinners.Tables[0].Rows[index].Delete(); \\deleting old row. dsWinners.Tables[0].Rows.InsertAt(newrow, index - 1); \\ adding new row. ...

Displaying data from a DataGridView on one Form into TextBoxes on another

c#,winforms,datagridview

@Harry Sweetman ok first to get the selected element of your datagridview you can make something like this: //recover the view row DataGridViewRow drv = (DataGridViewRow)dataGridBasket.Current; //if the row is not empty => basket was selected in the dataGridView if (drv.Cells[0].Value != null) { //Here we get the first cell...

Changing date format in datagridview

c#,excel,datagridview,date-format

If you are using SQL Server, try to set the datatype of those columns to Date instead of DateTime.

Gridview row count with condition [closed]

c#,winforms,datagridview

You may just need these 3 lines for your requirement, and not any database operations. dataGridView1.DataSource = ds.Tables[0]; lbltotalfemale.Text = ds.Tables[0].Select("Gender='female'") .Count().ToString(); lbltotalmale.Text = ds.Tables[0].Select("Gender='male'") .Count().ToString(); Hope this helps......

Displaying rows from table into datagridview with matched column value

c#,datagridview,datatable

You can use the IN SQL key word: DBConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=FacesDatabase.mdb"; DBConnection.Open(); OleDbCommand command = new OleDbCommand(); command.Connection = DBConnection; string query = "Select FaceID,FaceName,RollNo,FaceImage from " + tableName + " where FaceName IN ('"+ string.Join("','",MatchName.ToArray())+ "')"; command.CommandText = query; OleDbDataAdapter da=new OleDbDataAdapter(command); DataTable dt=new DataTable(); da.Fill(dt); dataGridView1.DataSource=dt;...

DataGridView anchors

c#,datagridview,anchor,windows-forms-designer

Yes, you can. Use MaxiumSize.Width, MaxiumSize.Height to set the maximum size of your control. You'll need to set minimum size as well using MinimumSize.Width and MinimumSize.Height properties. ...

How to display entered string from textbox in ordered list in c#?

c#,datagridview

Complete sample form code: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinForm { public partial class frmMain : Form { /// <summary> /// form constructor /// </summary> public frmMain() { InitializeComponent(); } private ListView listView; private TextBox textBox;...

How to Register the RowLeave event

c#,winforms,datagridview

But I don't know how to do this with RowLeave. Any suggestions? I can't find any examples or find it in the docs. I found the method in the docs but not how to register the event handler DataGridView has a RowLeave event property that you can subscribe to...

Receiving error “no database selected” when trying to query DB [closed]

c#,mysql,datagridview

Your connection string should specify a database name: Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword; ^^^^^^^^^^^^^^^^^^^ (Port 3306 is the default MySql port) Ref. MySQL connection strings...

Restricting the input in DataGridView c#

c#,datagridview,combobox

When you create the columns, create them each as a DataGridViewComboBoxColumn. As you stated: [You] know the expected values for each column Therefore you can create the columns this way with each column's source bound. For example: public Form1() { InitializeComponent(); List<List<string>> options = new List<List<string>>() { new List<string>() {...

Uploading excel file to DataGridView

c#,excel,datagridview

One way of doing this is to use range in your select query. For example if you want to upload only specific content you can use the following query "Select * from [" + textBox2.Text + "$[A1:C100]" Where A1 and C100 are start and end cell numbers. You can dynamically...

Stopping / cancelling BackgroundWorker

c#,multithreading,winforms,datagridview

You have to keep your workers in order to stop them. Save them in a dictionary with the identifier of the row as a key: Dictionary<string, BackgroundWorker> workers = new Dictionary<string,BackgroundWorker>(); Then, for each worker you need to add the handler for the RunWorkerCompleted event in which you remove the...

Selecting and highlight a DataGridView row by checking a checkbox

powershell,checkbox,datagridview

To highlight a row, you just need to set the Selected property to $true: $dataGridView.Rows[$n].Selected = $true To do it when a checkbox is checked, we'll need to add some code to handle the selection when a corresponding event occurs. According to the documentation for the DataGridView.CellClick event (emphasis added):...

Cannot make DataGridView to bind to data source more than once

c#,multithreading,winforms,data-binding,datagridview

DataGridView will not update, because you using same instance of list for setting .DataSource(DataGridView Reference source) Then List<T> does not support notifications of the changes in the collection. DataGridView will never know about changes in the list Use BindingList<T> instead, then it is enough to bind it to DataSource only...

How to Require Confirmation on Form Close When there is Changed Data in a DataGridView

c#,winforms,datagridview

If you're doing databinding to a DataSource, then you can use the datasource to determine whether it has been changed in the FormClosing or FormClosed event. The actual implementation would be up to the type of datasource you are using. If you're not specifying a datasource, then the data by...

How to get value from dataGridView which is imported from .xls file

asp.net,vb.net,gridview,datagridview

I inspired with your answer. So, here is my resolution : For data As Integer = 0 To InvestorGridView.Rows.Count - 1 Response.Wri‌​te(InvestorGridView.Rows(data).Cells(0).Text) Response.Wri‌​te(InvestorGridView.Rows(data).Cells(1).Text) Response.Wri‌​te(InvestorGridView.Rows(data).Cells(2).Text) Next ...

Filtering by user input getting error message can not get table 0

c#,visual-studio-2013,datagridview

Remove the spaces from the name of the datatable in dataadapter.Fill(ds, "pricingtable"); ...

Null values are creating error in datagridview in vb.net

vb.net,excel,datagridview

You can insert an If condition to first evaluate if the cell contents are dbnull. Here is an example where I use it in some of my own projects: If IsDBNull(part.Item("Assignment Category")) = False Then newOracleHREmployeeRecord.AssignmentCategory = CStr(part.Item("Assignment Category")) End If ...

Array of DataGridViews in C#

c#,winforms,datagridview

If you're generating the DataGridViews dynamically then you can use exactly the approach you propose. Instances of controls on a form are objects in C# like any other, so you can hold a reference to those objects in an array. Not knowing much of your code, this is a bit...

How to filter and show only selected items in datagridview?

c#,checkbox,datagridview

The idea is to have a button which when clicked, a loop will be executed over GridView Rows. Within the loop we will check whether the CheckBox for that row is checked, if the CheckBox is checked then the Value from the GridView Row Cell and Cell controls like Label,...

Create a DataGrid in WPF with column type equal with DataGridViewButtonColumn of WinForm

c#,wpf,datagridview,wpfdatagrid

Here is an extremely simple example : <Window x:Class="DataGridUpdateSourceTriggerOneWay.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DataGridUpdateSourceTriggerOneWay" Title="MainWindow" Height="350" Width="525"> <Grid> <DataGrid x:Name="DataGrid1" IsReadOnly="False" AutoGenerateColumns="False" CanUserAddRows="False" ItemsSource="{Binding data}"> <DataGrid.Columns>...

Datagridview : row moves after an update, why?

.net,vb.net,postgresql,datagridview,odbc

this is an expected behaviour as stated by postgresql documentation: 8.If the ORDER BY clause is specified, the returned rows are sorted in the specified order. If ORDER BY is not given, the rows are returned in whatever order the system finds fastest to produce. if you don't specify a...

Get all last transactions and sum all and view in datagridview

sql,vb.net,datagridview

You can try following query:- SELECT SUM(AMOUNT) FROM TABLE1 WHERE in_DATE IN (SELECT to_DATE FROM (SELECT EmployeeID, MAX(in_Date) AS to_DATE FROM TABLE1 GROUP BY EmployeeID) TAB1 ) ...

How can I create a footer for cell in datagridview

c#,winforms,datagridview,cell

To create DataGridView cells with extra content you need to code the CellPainting event. First you set up the cells to have enough room for the extra content and layout the normal content as you wish..: DataGridView DGV = dataGridView2; // quick reference Font fatFont = new Font("Arial Black",...

How can I make DataGridView.Rows.DividerHeight work?

c#,.net,winforms,datagridview

Your code works just fine. With a few extra touches it looks like this: This is basically your code, applied to a normal DataGridView freshly dropped to the form..: private void button1_Click_1(object sender, EventArgs e) { dataGridView1.DataSource = null; dataGridView1.Rows.Clear(); dataGridView1.Columns.Clear(); sudokuTable = getTable(); dataGridView1.DataSource = sudokuTable; for (int i...

update multi-table dataset via datagridview vb

xml,vb.net,datagridview,dataset

Here is vbnet Imports System Imports System.Collections.Generic Imports System.Linq Imports System.Text Imports System.Xml Imports System.Xml.Serialization Imports System.Xml.Schema Imports System.IO Public Class Form1 Const FILENAME1 As String = "c:\temp\test.xml" Const FILENAME2 As String = "c:\temp\test2.xml" Dim mameconfig As Mameconfig = Nothing Dim dt As DataTable = Nothing Sub New() ' This...