I have a table with 6 columns ID,A,B,C,D and E. ID is primary key.
An third party application keep updating Column D and E and also
adding new rows to the table.
I want to display this table to a datagridview control. I am trying to update it each after 5 sec. So far i have tried:
Table may have 3-100 records.
//dt is a DataTable with new data
//dtPos is DataTable currently bind to datagridview
foreach (DataRow r in dt.Rows)
{
dtPos.DefaultView.RowFilter = "ID = '" + r["ID"].ToString() + "'";
if (dtPos.DefaultView.Table.Rows.Count > 0)
{
dtPos.DefaultView.Table.Rows[0]["D"] = r["D"];
dtPos.DefaultView.Table.Rows[0]["E"] = r["E"];
}
else
{
dtPos.Rows.Add(r);
}
}
This did not seem to work as expected. any better idea?
hi i suggest you to do above your task in gridview itself so you can do it instantly insteed of doing it in table and then assigning it back to the datagridview.
dgv have add row method so you can add row in dgv directly .
use like this when u need to add new row
dgv.Rows.Add(1,2,3,4,4,5);
and when u need to change the value of the cell then
dgv.rwos[roindex].cells[cellindex].value = xxx; //your new value;
this can help u ....
Related
I Have requirement to fill the datagridview row by row . i.e. if 3rd row is currently selected then data needs to be filled in 3rd row (my query returns always single row ) . same for every row.
some what like
DataTable dt = new DataTable();
dataadapter.Fill(dt);
dataGridView1.Rows[index].DataSource = dt; (just a hunch, but not working)
(instead of ) //dataGridView1.DataSource = dt;
hope that I made my requirement clear to you
Is their any way to accomplish it ....
Thanks in advance....
If your query returns a single row then you just have to fill the columns with correct values from your query:
dataGridView1.Rows[rowIndex].Cells["ColumnName"].Value =
dt.Rows[0]["ColumnNameInDataTable"].ToString();
Your grid will not be bound to the data this way. But it will fill the columns in the current row like you've asked.
I don't think this is possible directly,
You could use a List with a certain amount of empty objects and bind this List to your DataGridView... Then you would have empty Rows to work with. You can then fill single rows of the List with data and update the binding.
I also think you need a BindingSource and not a DataTable in this case...
Something like this:
private List<YourObject> gridData; // List
private BindingSource bindingSource;
public void Init()
{
this.gridData = new List<Anything>();
//prefill list, in this case we want to have 100 empty rows in DataGrid
for (var i = 0; i < 100; i++)
{
this.gridData.Add(new YourObject());
}
this.bindingSource.DataSource = this.gridData;
}
public void UpdateRow(int row)
{
this.gridData[row] = (from .. in select ...).FirstOrDefault(); // your query
}
In my WinForms application I'm populating two DataGridView's like below;
private void PopulateData()
{
//Load data
DataTable dtAll = LoadData();
DataTable dtSelected = dtAll.Clone();
dtAll.PrimaryKey = new DataColumn[] { dtAll.Columns["PK"] };
dtSelected.PrimaryKey = new DataColumn[] { dtSelected.Columns["PK"] };
DataView leftGridView = new DataView(dtAll);
DataView rightGridView = new DataView(dtSelected);
dgvLeft.AutoGenerateColumns = false;
dgvLeft.DataSource = leftGridView;
dgvRight.AutoGenerateColumns = false;
dgvRight.DataSource = rightGridView;
}
Then in some other place I'm exchanging columns between two DataGridView like below;
private void ExchangeData()
{
//Get current row of left grid
DataRow selectedRow = ((DataRowView)dgvLeft.CurrentRow.DataBoundItem).Row;
//Find the row from all data table
DataRow foundRow = dtAll.Rows.Find(selectedRow["PK"].ToString());
if (foundRow == null)
return;
//Exchange row between grids
dtAll.Rows.Remove(foundRow);
dtSelected.ImportRow(foundRow);
}
But only dtAll.Rows.Remove(foundRow); is completing correctly and reflected in the DataGridView but the line dtSelected.ImportRow(foundRow); doesn't add the row to dtSelected. I changed this line to dtSelected.ImportRow(selectedRow); but the result is same. Any thoughts?
In MSDN something catches my attention was;
If the new row violates a Constraint it won’t be added to the data
table.
Note: This question is not related to following SO posts;
DataTable.ImportRow is not adding rows
Why DataTable.Rows.ImportRow doesn't work when passing new created DataRow?
DataTable importRow() into empty table
ImportRow is not working
EDIT: I added the PrimaryKey part, DataView and DataRowCollection.Find method later to incorporate some filtering feature. Without these the code worked as intended.
Another EDIT: I removed the PrimaryKey part from PopulateData method and modified the ExchangeData method as follows;
//Get current row of left grid
DataRow selectedRow = ((DataRowView)dgvLeft.CurrentRow.DataBoundItem).Row;
//Find the row from all data table
int foundRow = dtAll.Rows.IndexOf(selectedRow);
//Exchange row between grids
dtAll.Rows.RemoveAt(foundRow);
dtSelected.ImportRow(selectedRow);
But the issue is same.
OK then it was because of my order of the code to execute. Let me explain.
This was the code I execute for the exchange;
//Exchange row between grids
dtAll.Rows.RemoveAt(foundRow);
dtSelected.ImportRow(selectedRow);
Here the row is first deleted before it's been imported to the dtSelected table. That's why dtSelected never got the row imported whatever the way I tried.
So changing the order of the code fixes my issue;
//Exchange row between grids
dtSelected.ImportRow(selectedRow);
dtAll.Rows.RemoveAt(foundRow);
The fear emotion in Inside Out says a phrase which suites this situation. "My Bad"
I am trying to save a new added row in a DataGridView to a database. I can't understand which method to call - either gridview1_UserAddedRow or gridview1_RowsAdded (what if it's just one row?).. So far, I've seen that gridview1_RowsAdded executes every time when the form loads.
The DataGridView is bound using a BindingList.
This is how the gridview1_UserAddedRow looks like:
private void dataGridView1_UserAddedRow(object sender, DataGridViewRowEventArgs e)
{
int lastRow = dataGridView1.Rows.Count - 2;
DataGridViewRow newRow = dataGridView1.Rows[lastRow];
bindinglist.Add(new MyTestClass{ ScheduleId = scheduleId, Name = Convert.ToString(newRow.Cells["Name"].Value),
Value = Convert.ToString(newRow.Cells["Value"].Value), TestId = testId});
}
Unfortunately, this doesn't work and nothing is inserted. Actually, I think this event is called when a new row is clicked. How else can I insert the newly created row in the database?
The code is not updating anything to the database as there is no code to update it.
You need to execute a query to update those new values. You could try using Commands:
http://msdn.microsoft.com/en-us/library/aa984369(v=vs.71).aspx
Or change the list to a DataTable, which allows you to update the values 'automatically' (a bit harder): http://msdn.microsoft.com/en-us/library/z1z2bkx2(v=vs.110).aspx
I would stay away form databinding, but if you can't, you can try this:
// Create a new row
DataRow dr = YourDataSet.Vendors.NewRow(); // Change 'Vendors' with your database table's name
// Add some data to your new row
dr[0] = 124;
// Insert the previous row
YourDataSet.Vendors.Rows.InsertAt(dr, 1); // Change the 1 to your index where you want to insert the data.
I have a DataTable which is bind to dataGridview in my code.
When I get datas from database, the gridview works fine. it fills with data.
What I want to do is getting the primary key value of the specified row.
Ex:
PK Address Phone
1 xxxyyyzzz... 1234567
2 aaabbbccc... 2345678
What I want is this. User will click on any row, then click on a button to add some stuff.
Then I will get PK value, and do other stuffs.
How can I do it?
Hmm can you specify how and when you are talking about getting this value?
You can do this:
int index = dt.Rows.IndexOf(row);
But I am not sure what the point of that would be, if you already have the specified row, why can't you just get the PK via row[columnName]?
But this is more resource intensive than just looping through with a for loop.
Do you need this before or after binding to the dataGridView? If you need to get the value from the dataGridView row that is different.
For your edit:
You would can get the selected row like so:
if (yourDataViewGrid.SelectedRows.Count == 1)
{
Int pk = yourDataViewGrid.Rows[yourDataViewGrid.SelectedRows[0].Index].Cells["PK"].Value.ToString();
}
If you are doing it by some other method like using a checkbox to select a row, you would do this:
foreach (DataGridViewRow row in YourDataGridView.Rows)
{
if ((Boolean)((DataGridViewCheckBoxCell)row.Cells["CheckBoxName"]).FormattedValue)
{
Int pk = rows.Cells["PK"].Value.ToString();
}
}
The DataGridView control binds to a DataTable using the DataView class. You can use something like this to get the DataRow of a DataGridViewRow
var vrow = (DataRowView)grid.Rows[12].DataBoundItem; // get the bound object
var drow = vrow.Row; // the Row property references the real DataRow
where 12 is the index you are looking for. Sometimes it helps to set the DataSource property to a DataView explicitly and keep a reference to it on your form. The view will know the sorting of the data too
var view = new DataView(table);
grid.DataSource = view;
I am getting the Data table a output from my DataAccess Layer.
In My Datatable I am getting users Name,Number,Qualification
I want to assign a users name,number,qualification to a textbox for a particular user id,
How can i do that.
Help
Suppose you got datatable dt from the DAL
Then
var row = from t in dt
where t["userId"]='userid'
select t;
since you got row related to a user now you can use it to assign to the textboxs
txtName.Text = row["Name"]
assuming the datatable has 1 row:
DataRow row = table.Rows[0];
textbox1.text = row["Name"];
textbox2.text = row["Number"];
and so on
if there are multiple rows in the datatable, you need to select the row with that particular used id
DataRow row = table.Select("ID=" + UserID.ToString());
You have to pay attention to NULL values and number of rows.
if (table.Rows.Count == 1)
{
DataRow row = table.Rows[0];
NameTextBox.Text = row.IsNull("name") ? string.Empty : row["name"];
NumberTextBox.Text = row.IsNull("number") ? string.Empty : row["number"];
}
else
{
// Deal with no rows from DL
}
Using ternary operator makes you sure, you delete content of TextBoxes in case you reload row within already filled up page.
Also you may consider to used typed dataset, and access to columns will be generated by xsd.exe.