How can I create a new DataGridView control for each new row in another datagridview in vb.net? - mysql

I have a DataGridView control (DataGridView6) that displays a list of managers. I want to generate a new DataGridView everytime I add a new manager to the list and put it in a specific place on my form.
EDIT:
say if i have a main datagridview, and i want to add another datagridview of the same size directly below it, how would i achieve this using the event handler method described in your answer below? im not sure if this is the most efficient way of displaying new members in the program though...
How do can I do this as simply as possible?

Use the DataGridView's "RowsAdded" event. Every time you add a new row (ie manager) to DataGridView6, have the event handler create a new DataGridView and place it where you want it.
It's hard to give a more detailed answer without the specifics of your implementation, but something like that should work.
EDIT - So something like this?
DataGridView dgv = new DataGridView();
dgv.Location = new Point(DataGridView6.Location.X,DataGridView6.Location.Y + <somevalue>);
If you need to keep adding them below this, you could just make a variable NextY that you increment each time you add a new one. You can store them all in a LinkedList or something similar so you can access them easily in order.

I'm not very good at VB, so I've written it in C# first:
DataGridView DataGridView6;
DataGridView DataGridView7;
DataGridViewRow CreateRow(object data) {
DataGridViewRow row = null;
int index = DataGridView6.Rows.Add();
row = DataGridView6.Rows[index];
// row.Cells[0] = something;
// basically, add your date
return row;
}
void DisplayManagerRow(DataGridViewRow row) {
DataGridView7.DataSource = null;
int columns = (DataGridView6.Columns != null) ? DataGridView6.Columns.Count : 0;
if ((row != null) && (0 < columns)) {
DataGridView7.Columns.Clear();
List<DataGridViewColumn> cols = new List<DataGridViewColumn>(columns);
for (int i = 0; i < columns; i++) {
DataGridViewColumn dgvCol = (DataGridViewColumn)DataGridView6.Columns[i].Clone();
DataGridView7.Columns.Add(dgvCol);
}
DataGridView7.Rows.Add(row);
}
}
Now, to try this in VB:
private DataGridView6 As DataGridView
private DataGridView7 As DataGridView
Private Function CreateRow(ByVal data As Object) As DataGridViewRow
Dim index As Int16 = DataGridView6.Rows.Add()
Dim row As DataGridViewRow = DataGridView6.Rows(index)
' row.Cells(0) = something
' basically, add your date
Return row
End Function
Private Sub DisplayManagerRow(ByVal row As DataGridViewRow)
DataGridView7.DataSource = Nothing
Dim columns As Int32 = 0
If Not (DataGridView6.Columns = Nothing) Then
columns = DataGridView6.Columns.Count
End If
If ((row Is Not Nothing) And (0 < columns)) Then
DataGridView7.Columns.Clear()
Dim cols As List<DataGridViewColumn> = new List<DataGridViewColumn>(columns)
For (Dim i As Int32 = 0; i < columns; i++)
Dim dgvCol As DataGridViewColumn = CType(DataGridView6.Columns(i).Clone(), DataGridViewColumn)
DataGridView7.Columns.Add(dgvCol)
Next For
DataGridView7.Rows.Add(row)
End If
End Sub
I can't even remember how to write a For loop in VB! Pathetic!
Does that get the point across, though?
Is this what you are trying to do?

Related

SSIS Excel Import (Column Names Changing)

I have an Excel file that loosely resembles the following format:
I'll explain the next step of the SSIS element first as the column names are not "important" as I am un-pivoting the data in a data flow to start getting it usable:
The issue is, the file will be updated - years and quarters will be removed (historical), new ones added to replace the old ones. That means, as we all know, the metadata on a data flow is broken.
The cell range and position etc. will always remain the same.
Is there a way it can be handled in a data flow with the column names (2016q1) being fluid?
Thanks
You're going to like this as it also does the pivot:
Using C# Script component source:
Add namespace:
Using System.Data.OleDb;
Add your 4 output columns and select data types:
Add code to new row section.
public override void CreateNewOutputRows()
{
/*
Add rows by calling the AddRow method on the member variable named "<Output Name>Buffer".
For example, call MyOutputBuffer.AddRow() if your output was named "MyOutput".
*/
string fileName = #"C:\test.xlsx";
string SheetName = "Sheet1";
string cstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
OleDbConnection xlConn = new OleDbConnection(cstr);
xlConn.Open();
OleDbCommand xlCmd = xlConn.CreateCommand();
xlCmd.CommandText = "Select * from [" + SheetName + "$]";
xlCmd.CommandType = CommandType.Text;
OleDbDataReader rdr = xlCmd.ExecuteReader();
//int rowCt = 0; //Counter
while (rdr.Read())
{
for (int i = 2; i < rdr.FieldCount; i++) //loop from 3 column to last
{
Output0Buffer.AddRow();
Output0Buffer.ColA = rdr[0].ToString();
Output0Buffer.ColB = rdr[1].ToString();
Output0Buffer.FactName = rdr.GetName(i);
Output0Buffer.FactValue = rdr.GetDouble(i);
}
//rowCt++; //increment counter
}
xlConn.Close();
}
If the columns remain in order, then you can skip header rows and select 1st row does not contain headers.

VB.net Autocomplete Textbox filter using mysql database as custom source

I'm Having a problem regarding to the autocomplete textbox. First I already made the autocomplete textbox work with mysql database as custom source but the default textfilter of autocomplete is "start with" not "contains". I want to change the textfilter to "contains", so that when I search any part of the string, the whole name which contains the searched word will appear in the autocomplete suggestions.
Can anyone help me fix my code?
This is the code i've done so far:
txtSearch.AutoCompleteMode = AutoCompleteMode.SuggestAppend
txtSearch.AutoCompleteSource = AutoCompleteSource.CustomSource
Dim DataCollection As New AutoCompleteStringCollection()
Dim query As String
sqlcon = New MySqlConnection
sqlcon.ConnectionString =
"server=localhost;userid=root;password=root;database=svfmemberlistdb"
Try
sqlcon.Open()
query = " SELECT Name FROM svfmemberlistdb.svfmemberlist "
sqlcmd = New MySqlCommand(query, sqlcon)
sqladr.SelectCommand = sqlcmd
sqladr.Fill(ds)
sqladr.Dispose()
sqlcon.Close()
For Each row As DataRow In ds.Tables(0).Rows
If row.ToString.Contains(txtSearch.Text) Then
DataCollection.Add(row(0).ToString())
End If
Next
Catch ex As Exception
End Try
txtSearch.AutoCompleteCustomSource = DataCollection
I quote here Mitja Bonca's answer on MSDN.
In this case, autocompletemode will just not do. Its code is not meant
for something like it.
You will have to do your own code, to do the filtering on each letter
press.
So I would suggest not to use autocompletemode, and get all the data
(names) into dataTable. When user presses some button ("1" for
example), you start with your filtering, by creating new Datatable
(leave the main one untached - so you can return back to all data when
clearing comboBox by backspace), with Copy() method - to create a full
copy of original one, and use Select method to do the filteing.
This should look something like by using % simbol on both sides of a
string - to filter inbetween - this is what you want!
DataTable AllNames = new DataTable();
//fill it up and leave it untouched!
//to filter comboBox with names that contains pressed characters do in
private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
string name = string.Format("{0}{1}", comboBox1.Text, e.KeyChar.ToString()); //join previous text and new pressed char
DataRow[] rows = table.Select(string.Format("FieldName LIKE '%{0}%'", name));
DataTable filteredTable = AllNames.Clone();
foreach(DataRow r in rows)
filteredTable.ImportRow(r);
comboBox1.DataSource = null;
comboBox1.DataSource = filteredTable.DefaultView;
comboBox1.DisplayMember = "FieldName";
}
Reference
EDIT: This is of course a c# answer not VB.NET but it might be helpful to get the concept.

Dynamic Div with a table asp.net

Is there a way to add a table and rows to a dynamically created div element?
Dim divTable As New HtmlGenericControl("div")
divTable.ID = "divTable"
divTable.Attributes("class") = "printtable"
divTable.InnerHtml = "<asp:Table ID=""table1"" CellPadding=""1"" runat=""server""> </asp:Table>"
divPlaceHolder.Controls.Add(divTable)
I need to add dynamic rows to table1 but obviously whenever i try to access table1 from the code file it says 'table1' not declared.
Help !
Why don't you add a Panel(which is rendered as a div) to the PlaceHolder or use just a Panel alone as container? You have to add the Table as server-control instance to that panel.
Dim divTable As New Panel()
divTable.ID = "divTable"
divTable.CssClass = "printtable"
divPlaceHolder.Controls.Add(divTable) ' the placeholder is redundant with a panel '
Dim table As New Table()
table.ID = "table1"
table.CellPadding = 1
divTable.Controls.Add(table)
You can find and access this table via FindControl:
Dim divTable As Panel = DirectCast(divPlaceHolder.Controls(0), Panel)
Dim table As Table = DirectCast(divTable.Controls(0), Table)
Remember that you need to recreate all dynamically created controls on every postback with the same ID's as before in Page_Load at the latest.
It won't as you are appending a String to your dynamically created div`.
Your apprach isn't correct try it this way.
Table table1= new Table();
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
cell1.Text = "blah blah blah";
row.Cells.Add(cell1);
table1.Rows.Add(row);
First of all your existing DIV need to have runat=server property. Then you are able call it from codebehind
<div id="divRunServer" runat="server"></div>
In codebehind call that control and use Table web ui control to create dynamic html element.
//prepare dynamic table
Table Table1 = new Table();
int numrows = 3;
int numcells = 2;
for (int j = 0; j < numrows; j++)
{
TableRow r = new TableRow();
for (int i = 0; i < numcells; i++) {
TableCell c = new TableCell();
c.Controls.Add(new LiteralControl("row "
+ j.ToString() + ", cell " + i.ToString()));
r.Cells.Add(c);
}
Table1.Rows.Add(r);
}
//add to div
divRunServer.Controls.Add(Table1)
Referred from

Creating object variables from string in AS3

I have the following issue related to how can i create an Object varible from a String name.
var obj_product:Object = new Object;
obj_product.product = producto.nombre_producto;
obj_product.products_proveedorID = product.ID;
obj_product.productID = product.productID;
obj_product.price = 0;
if ( _extra_headers.length > 0 && _extra_headers[0].length > 0)
for (var index:int=0; index < _extra_headers.length; index++ )
obj_product._extra_headers[index] = 0;
_extra_headers is an Array where I hold new header names in the Datagrid, so for every new name I need to create its variable within the object.
Whats should I do?
I'm not an ActionScript programmer, but on the assumption that it's close enough to JavaScript, replace the last line with this:
obj_product[_extra_headers[index]] = 0

Remove multiple rows in a single pass in JTable AbstractDataModel

i've got an issue with Jtable and my dataModel.
My table model extends AbstracttableModel, the datas are stored in a Vector.
I'have a function witch is suppose to remove one or more row.
These rows are not necessarily contiguous because my jtable set a selectionMode as this:
jTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
The function to remove row (one by one):
public void removeMessageRow(Integer p_idMessage) {
Enumeration<MlMessage> alldatas = vData.elements();
while (alldatas.hasMoreElements()) {
MlMessage m = alldatas.nextElement();
if (m.getIdMessage() == p_idMessage) {
int idx = vData.indexOf(m);
boolean result = vData.remove(m);
// fireTableDataChanged();
// fireTableRowsDeleted(idx, idx);
fireTableStructureChanged();
return;
}
}
When i launch the function, i execute the loop without problem, in step-by-step mode, i can see the vData object updated and if i execute this only one time there is no probleme with the GUI. The problem appear when i select more than one row.
For example, i selected row number 0 and number 1 in my table and i lauch the function removeMessageRow, at the first execution, the vDataObject is correctly updated (all the datas are shiffted and the last elements of this vector is set to null by the call to vData.remove(m).
So in my case, i expect that at the second execution, the object to find should be at position 0 but it's at position 1 as the vData Object as never been updated.
Does anybody have an idea about that?
I've tried many on fire... stuff but no one semms to execute immediatly.
Thanks for any help by advance and sorry for my Shakespeare's language.
Add a method in your model taking a collection of indices to remove (Set<Integer>, or int[]), sort this collection, iterate backwards in this collection, and remove the elements in the list of objects of your model:
public void removeRows(int[] indices) {
Arrays.sort(indices);
for (int i = indices.length - 1; i >= 0; i--) {
this.data.remove(indices[i]);
fireTableRowsDeleted(indices[i], indices[i]);
}
}
int[] selectedRow = tblUsuarios.getSelectedRows();
int del=1;
for(int j=0; j<selectedRow.length; j++){
modTabla.removeRow(selectedRow[j]);
if(j<selectedRow.length-1){
selectedRow[j+1] = selectedRow[j+1]-del;
del = del+1;
}
}
//modTabla = defaultTableModel
//tblUsuarios = jtable