Category: .NET

VB.NET – Générer / Créer DataTable depuis un DataGridView avec les champs visibles + leurs ordres

”’ <summary>
”’ Retourne un DataTable rempli avec les colonnes visible d’un datagridview.
”’ </summary>
”’ <param name=”dgv”>DataGriView source</param>
”’ <returns></returns>
Public Function genererDataTableDepuisDataGridView(dgv As DataGridView) As DataTable
Dim dt = New DataTable()
Dim a As Integer = 0
‘ Crée les colonnes du DataTable à retourner avec les colonnes visibles du DataGridView.
For a = 0 To dgv.ColumnCount Step 1
For Each col As DataGridViewColumn In dgv.Columns
If a = col.DisplayIndex Then
If col.Visible = True Then
dt.Columns.Add(col.Name)
End If
End If
Next
Next
‘ crée un object d’un longueur égale au dataTable que l’on viens de créer.
Dim Values As Object() = New Object(dt.Columns.Count – 1) {}
‘ pour chaque ligne du dataGridView et pour chaque colonne on rempli la valeur.
For Each row As DataGridViewRow In dgv.Rows
Dim i As Integer = 0
For Each dc As DataColumn In dt.Columns
If dgv.Columns(row.Cells(dc.ColumnName).ColumnIndex).Visible = True Then
Values(i) = row.Cells(dgv.Columns(dc.ColumnName).Index).Value
i += 1
End If
Next
dt.Rows.Add(Values)
Next
Return dt
End Function

VB.NET – Replacer les caractères spéciaux d’une chaine string

Dim chaine As String = “/-?:(),+àsdsdqd  áâãäåfdsg  dfgÀÁÂdfgà ÄÅéèêëËÊÉdfgAZAZAZFGGÈòóôõöÒÓÔÕÖùúûüÙÚÛÜìíîïÌÍÎÏÿýÝçÇ”
Dim chaine_final As String = “”
Dim non_autorise As Char() = “/-?:(),+àáâãäåÀÁÂÃÄÅéèêëËÊÉÈòóôõöÒÓÔÕÖùúûüÙÚÛÜìíîïÌÍÎÏÿýÝçÇ”.ToCharArray()
Dim autorise As Char() = “/-?:(),+aaaaaaAAAAAAeeeeEEEEoooooOOOOOuuuuUUUUiiiiIIIIyyYcC”.ToCharArray()

Dim i As Integer = 0
For Each s As String In chaine
For Each a As String In autorise
If i = non_autorise.Length Then
Exit For
End If
If s = non_autorise(i) Then
chaine = chaine.ToString.Replace(non_autorise(i), a)
End If
i += 1
Next
i = 0
Next

 

 

En faire une fonction :

Public Function remplacementCaractereSpeciaux(pChaineAModifier As String, pCaractereAutorise As String, pCaractereNonAutorise As String)

Dim chaine As String = pChaineAModifier
Dim non_autorise As Char() = pCaractereNonAutorise.ToCharArray()
Dim autorise As Char() = pCaractereAutorise.ToCharArray()

Dim i As Integer = 0
For Each s As String In chaine
For Each a As String In autorise
If i = non_autorise.Length Then
Exit For
End If
If s = non_autorise(i) Then
chaine = chaine.ToString.Replace(non_autorise(i), a)
End If
i += 1
Next
i = 0
Next

Return chaine

End Function

Crystal report – Evenement sur bouton imprimer du crystalviewer

‘Permet de trouver le bouton qui à été cliquer dans le Crystal report viewer
‘ et de lui rajouter un événement
For Each Ctrl As Control In Me.CrystalReportViewer1.Controls
If TypeOf Ctrl Is ToolStrip Then
For Each Obj As Object In CType(Ctrl, ToolStrip).Items
If TypeOf Obj Is ToolStripButton Then
AddHandler CType(Obj, ToolStripButton).Click, AddressOf printButton_Click
End If
Next
End If
Next

Private Sub printButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)

End Sub

 

VB.NET -Excel Créer / Sauvegarder / Fermer

Assembly à utiliser :

Imports Microsoft.Office.Interop.Excel

Code :

Dim excel As Application = Nothing
Dim mFichier As String = “”
Dim wb As Microsoft.Office.Interop.Excel.Workbook

Private Sub objExcelcreate()
Try
mFichier =”monfichier.xlt”
excel = New Application
wb = excel.Workbooks.Open(mFichier )
excel.Visible = True
excel.DisplayAlerts = False

‘ EVENEMENT POUR DECTECTER LA FERMETURE ET  FERMER EXCEL
Try
AddHandler excel.WorkbookBeforeClose, AddressOf myExcel_Quit
Catch ex As Exception
End Try

Catch ex As Exception
MessageBox.Show(ex.Message.ToString)
End Try
End Sub

‘ FERMER EXCEL

Private Delegate Sub delegExcel()

Public Sub myExcel_Quit()
If Me.InvokeRequired Then
Me.Invoke(New delegExcel(AddressOf excel_Close))
End If
End Sub

‘ FERMER EXCEL
Public Sub excel_Close()

‘SAUVEGARDER LE FICHIER

wb.SaveAs(monfichier.xlt)
excel.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(wb)
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel)
GC.Collect()
End Sub

 

 

 

 

 

 

WCF – VB.NET – Envoyer / uploader un fichier en WCF

WEB.Config :

<?xml version=”1.0″ encoding=”utf-8″?>

<!–
Pour plus d’informations sur la configuration de votre application ASP.NET, consultez
http://go.microsoft.com/fwlink/?LinkId=169433
–>

<configuration>
<system.web>
<compilation debug=”true” strict=”false” explicit=”true” targetFramework=”4.0″ />
<httpModules>
<add name=”ApplicationInsightsWebTracking” type=”Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web” />
</httpModules>
<!– ajouté–>
<httpRuntime executionTimeout=”90″ maxRequestLength=”1000000000″ />

</system.web>
<system.webServer>

<!– ajouté–>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength=”2147483648″ />
</requestFiltering>
</security>

<validation validateIntegratedModeConfiguration=”false” />
<modules>
<remove name=”ApplicationInsightsWebTracking” />
<add name=”ApplicationInsightsWebTracking” type=”Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web” preCondition=”managedHandler” />
</modules>
</system.webServer>

<runtime>

<assemblyBinding xmlns=”urn:schemas-microsoft-com:asm.v1″>
<dependentAssembly>
<assemblyIdentity name=”System.Runtime” publicKeyToken=”b03f5f7f11d50a3a” culture=”neutral” />
<bindingRedirect oldVersion=”0.0.0.0-2.6.8.0″ newVersion=”2.6.8.0″ />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name=”System.Threading.Tasks” publicKeyToken=”b03f5f7f11d50a3a” culture=”neutral” />
<bindingRedirect oldVersion=”0.0.0.0-2.6.8.0″ newVersion=”2.6.8.0″ />
</dependentAssembly>
</assemblyBinding>

</runtime>

<system.serviceModel>
<!– ajouté–>
<bindings    >
<basicHttpBinding  >
<binding   transferMode=”Streamed”  maxReceivedMessageSize=”2147483647″ maxBufferSize=”2147483647″ maxBufferPoolSize=”2147483647″>
<readerQuotas maxDepth=”64″ maxArrayLength=”2147483647″ maxStringContentLength=”2147483647″/>
</binding>
</basicHttpBinding>
</bindings>

<behaviors>
<serviceBehaviors   >
<behavior name=””   >
<serviceMetadata httpGetEnabled=”true”       />
<serviceDebug includeExceptionDetailInFaults=”false”       />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled=”true”      />
</system.serviceModel>
</configuration>

 

Interface du wcf :
<OperationContract()>
Sub setExe(ByVal fichierStream As Stream)

Source .VB du wcf : 

Public Sub setExe(fichier As Stream) Implements ISvcCyrus.setExe
Dim fileStream = New FileStream(“\\data\CyrusApplication\developpement\maj\Cyrus2.exe”, FileMode.Create, FileAccess.Write)
fichier.CopyTo(fileStream)
fileStream.Dispose()
End Sub

Client  pour envoyer le fichier :

Dim service As New ServiceReference1.MonServiceClient
service.Endpoint.Address = New ServiceModel.EndpointAddress(“http://x.x.x.x/monService.svc&#8221;)

Dim stream As FileStream = File.OpenRead(cheminFichier)
service.setExe(stream)
 

VB.NET – Masque de saisie de date dans un datagridview en winform

Sub New()

‘ Cet appel est requis par le concepteur.
InitializeComponent()

Dim dt As New DataTable
dt.Columns.Add(“a”)
dt.Columns.Add(“Date”)

Dim dr1 As DataRow = dt.NewRow
dr1.Item(“Date”) = “10/03/2013”
Dim dr2 As DataRow = dt.NewRow
dr2.Item(“Date”) = “10/03/2013”

dt.Rows.Add(dr1)
dt.Rows.Add(dr2)

MDataGridView1.DataSource = dt
afficheDataGrid(MDataGridView10, False)

maskedTextBox2 = New MaskedTextBox
With maskedTextBox2
.Mask = “00/00/0000”
.Visible = False
End With
MDataGridView10.Controls.Add(maskedTextBox2)

End Sub

Const nomColonne As String = “Date”
Private WithEvents maskedTextBox2 As MaskedTextBox

Private Sub MyDataGridView1_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles MDataGridView10.CellBeginEdit
If (Me.MDataGridView10.Columns(e.ColumnIndex).Name = nomColonne) Then
Dim rect2 As Rectangle = Me.MDataGridView10.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True)
Me.maskedTextBox2.Size = rect2.Size
Me.maskedTextBox2.Location = rect2.Location
If (Me.MDataGridView10.CurrentCell.Value IsNot Nothing) Then
Me.maskedTextBox2.Text = Me.MDataGridView10.CurrentCell.FormattedValue.ToString()
End If
Me.maskedTextBox2.Visible = True
End If
End Sub

Private Sub MyDataGridView1_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles MDataGridView10.CellEndEdit
If (Me.MDataGridView10.Columns(e.ColumnIndex).Name = nomColonne) Then
Me.MDataGridView10.CurrentCell.Value = maskedTextBox2.Text
Me.maskedTextBox2.Visible = False
End If
End Sub

Private IsHandleAdded2 As Boolean

Private Sub MyDataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles MDataGridView10.EditingControlShowing
If Not IsHandleAdded2 And (Me.MDataGridView10.Columns(Me.MDataGridView10.CurrentCell.ColumnIndex).Name = nomColonne) Then
Dim tx As TextBox = CType(e.Control, TextBox)
AddHandler tx.KeyPress, AddressOf Me.tx_KeyPress
IsHandleAdded2 = True
End If
End Sub

Private Sub tx_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
If (Me.MDataGridView10.Columns(Me.MDataGridView10.CurrentCell.ColumnIndex).Name = nomColonne) Then
e.Handled = True
Me.maskedTextBox2.Focus()
If (Char.IsNumber(e.KeyChar)) Then
Me.maskedTextBox2.Text = e.KeyChar.ToString()
Else
Me.maskedTextBox2.SelectAll()
End If
End If
End Sub

VB.NET – Multi Thread

Background worker :

If not bw.IsBusy Then
bw.RunWorkerAsync()
End If

Friend WithEvents bw As New System.ComponentModel.BackgroundWorker

Private Sub bw_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles bw.DoWork
End Sub

Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bw.RunWorkerCompleted

Dim mForm As New Form1()
mForm.BringToFront()
mForm.TopMost = True
mForm.Owner = Me
mForm.Show()

End Sub

 

Delegate :

Dim deleg1 As SomeWorkDelegate = New SomeWorkDelegate(AddressOf AfficherDelegate)
FaireDelegate(deleg1)

Public Delegate Sub SomeWorkDelegate(ByVal strSomeString As String)

Sub AfficherDelegate()
End Sub

Public Sub FaireDelegate(ByVal someDelegateFunc As SomeWorkDelegate)
Dim mFormChrono As New TempsPasse()
mFormChrono.BringToFront()
mFormChrono.TopMost = True
mFormChrono.Owner = Me
mFormChrono.Show()
End Sub

 

VB.NET – Liste déroulante dans un datagrid, problème plusieurs cliques

 

Sur l’événement CellClick du datagrid :

 

dg.BeginEdit(True)

If dg.Rows(e.RowIndex).Cells(“NomDeLaCOlonne”).Selected = True Then

If dg.EditingControl IsNot Nothing Then

If dg.EditingControl.ToString().Contains(“System.Windows.Forms.DataGridViewComboBoxEditingControl”) Then

DirectCast(dg.EditingControl, DataGridViewComboBoxEditingControl).DroppedDown = True

End If

End If

End If

VB.NET – Créer une instance / classe depuis son nom

Dim mUserControl As UserControl = Nothing

If mExist = False Then

mUserControl = New UserControl

Dim mUserControlName As String = “nomSolution.nomClasse”

Dim T As Type = Type.GetType(mUserControlName, False, True)

Dim pParam As New Object

pParam = New Object() {mParent, mParent.getIdAffaire, mParent.getConn}

mUserControl = CType(Activator.CreateInstance(T, pParam), Object)