not taking all images after editing from data grid view in vb.net winform application - vb.net

I am working on windows form application.
in cell content click i wrote code like this:
If e.ColumnIndex = 4 Then
Dim OFDLogo As New OpenFileDialog()
OFDLogo.Filter = "JPEG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp"
If OFDLogo.ShowDialog() = DialogResult.OK Then
gv.Rows(e.RowIndex).Cells(4).Value = Image.FromFile(OFDLogo.FileName)
End If
End If
and save button i wrote code like this:
Dim cmpny As String = "Delete from CompanyMaster_tbl"
Exetransaction(cmpny)
For i As Integer = 0 To gv.RowCount - 2
sqlInsertT2 = "Insert Into DepartmentMaster_tbl(dtname,dtphone,dtEmail,Cid) Values ('" + myTI.ToTitleCase(gv.Rows(i).Cells(1).Value) + "','" + gv.Rows(i).Cells(2).Value + "','" + gv.Rows(i).Cells(3).Value + "'," & Ccid & ");"
Exetransaction(sqlInsertT2)
Dim departmnt As String = gv.Rows(i).Cells(1).Value
Dim departid As Integer = RecordID("dtId", "DepartmentMaster_tbl", "dtName", departmnt)
Dim sql As String
'----------------------------------
Dim image As Image = TryCast(gv.Rows(i).Cells(4).Value, Image)
If image IsNot Nothing Then
Dim ms As New MemoryStream()
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
Dim imagedata As Byte() = ms.ToArray()
sql = "update DepartmentMaster_tbl set empimage=#photo where dtId='" & departid & "'"
Dim cmd As New SqlCommand(sql, con.connect)
cmd.Parameters.Add("#photo", SqlDbType.Image)
cmd.Parameters("#photo").Value = imagedata
cmd.ExecuteNonQuery()
con.disconnect()
End If
Next
in first time i can able to save all images form data grid view..but again i load the same page ,and i try to edit one image,,after that again i try save all images from data grid view..but thise time only saving edited image .i mean(that time thise line of code not working proper)
Dim image As Image = TryCast(gv.Rows(i).Cells(4).Value, Image)
In cell content click I am taking row_index..that s why happen

check this solution
Sub refreshgrid()
Dim cd As SqlCommandBuilder = New SqlCommandBuilder(adapter)
adapter = New SqlDataAdapter("select c.cid,c.CompanyName,d.dtId,d.dtName as Department,d.dtPhone as Phone,d.dtEmail as Email,d.empimage,0 as flag from CompanyMaster_tbl c join DepartmentMaster_tbl d on c.Cid=d.cId order by cid", con.connect)
dt1 = New DataTable
bSource = New BindingSource
adapter.Fill(dt1) 'Filling dt with the information from the DB
bSource.DataSource = dt1
gv.DataSource = bSource
gv.Columns("cid").Visible = False
gv.Columns("dtId").Visible = False
Dim img As New DataGridViewImageColumn
img.HeaderText = "Image"
gv.Columns.Insert(6, img)
For i As Integer = 0 To gv.Rows.Count - 1
gv.Rows(i).Cells(6).Value = gv.Rows(i).Cells(7).Value
Next
gv.Columns("empimage").Visible = False
For i As Integer = 0 To gv.Rows.Count - 2
If Not IsDBNull(gv.Rows(i).Cells(6).Value) Then
gv.Rows(i).Height = 75
Dim column As DataGridViewColumn = gv.Columns(6)
column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
End If
Next
GenerateUniqueData(1)
End Sub
Private Sub btnupdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnupdate.Click
adapter = New SqlDataAdapter()
Dim cid As Integer
Dim dtid As Integer
Dim cmpname As String
Dim dtname As String
Dim dtPhone As String
Dim dtEmail As String
Dim dtimage As Image
For i As Integer = 0 To gv.RowCount - 2
' Dim rv = DirectCast(bSource.Current, DataRowView)
If (gv.Rows(i).Cells(8).Value = 1) Then
Dim rv = DirectCast(gv.Rows(i).DataBoundItem, DataRowView)
cid = rv.Row.Field(Of Integer)("Cid")
dtid = rv.Row.Field(Of Integer)("dtId")
cmpname = rv.Row.Field(Of String)("CompanyName")
dtname = rv.Row.Field(Of String)("Department")
dtPhone = rv.Row.Field(Of String)("Phone")
dtEmail = rv.Row.Field(Of String)("Email")
'Using ms As New MemoryStream(rv.Row.Field(Of Byte())("empimage"))
' dtimage = New Bitmap(ms)
'End Using
adapter.UpdateCommand = New SqlCommand("UPDATE CompanyMaster_tbl SET CompanyName = #CompanyName", con.connect)
'this code for updating image also..
adapter.UpdateCommand = New SqlCommand("update DepartmentMaster_tbl set dtName = #dtName,dtPhone = #dtPhone,dtEmail = #dtEmail,empimage=#dtimage where dtId=#dtid", con.connect)
' adapter.UpdateCommand = New SqlCommand("update DepartmentMaster_tbl set dtName = #dtName,dtPhone = #dtPhone,dtEmail = #dtEmail where dtId=#dtid", con.connect)
adapter.UpdateCommand.Parameters.AddWithValue("#Cid", cid)
adapter.UpdateCommand.Parameters.AddWithValue("#CompanyName", cmpname)
adapter.UpdateCommand.Parameters.AddWithValue("#dtId", dtid)
adapter.UpdateCommand.Parameters.AddWithValue("#dtName", dtname)
adapter.UpdateCommand.Parameters.AddWithValue("#dtPhone", dtPhone)
adapter.UpdateCommand.Parameters.AddWithValue("#dtEmail", dtEmail)
'Dim md As New MemoryStream()
'dtimage.Save(md, System.Drawing.Imaging.ImageFormat.Gif)
' Dim imagedata As Byte() = md.ToArray()
'Dim md As New MemoryStream()
'' Save to memory using the Jpeg format
'dtimage.Save(md, ImageFormat.Gif)
' read to end
'Dim bmpBytes As Byte() = md.GetBuffer()
' Dim image As Byte() = System.IO.File.ReadAllBytes()
Dim image As Image = TryCast(gv.Rows(i).Cells(6).Value, Image)
If image IsNot Nothing Then
Dim ms As New MemoryStream()
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
Dim imagedata As Byte() = ms.ToArray()
adapter.UpdateCommand.Parameters.AddWithValue("#dtimage", imagedata)
End If
'adapter.UpdateCommand.Parameters.AddWithValue("#dtimage", dtimage)
adapter.UpdateCommand.ExecuteNonQuery()
End If
Next
End Sub
Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
Me.Close()
End Sub
Private Sub gv_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles gv.CellContentClick
If e.ColumnIndex = 6 Then
Dim OFDLogo As New OpenFileDialog()
OFDLogo.Filter = "JPEG(*.jpg)|*.jpg|BMP(*.bmp)|*.bmp"
If OFDLogo.ShowDialog() = DialogResult.OK Then
gv.Rows(e.RowIndex).Cells(6).Value = Image.FromFile(OFDLogo.FileName)
gv.Rows(e.RowIndex).Cells(8).Value = "1"
End If
End If
End Sub
Private Sub Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Save.Click
For i As Integer = 0 To gv.RowCount - 2
If gv.Rows(i).Cells(1).Value.ToString.Length <> 0 AndAlso Not IsDBNull(gv.Rows(i).Cells(1).Value) Then
If gv.Rows(i).Cells(3).Value.ToString.Length = 0 OrElse IsDBNull(gv.Rows(i).Cells(3).Value) Then
MsgBox("Please Enter Department Details")
Exit Sub
End If
End If
Next
'Dim deprt As String = "Delete from DepartmentMaster_tbl"
'Exetransaction(deprt)
'Dim cmpny As String = "Delete from CompanyMaster_tbl"
'Exetransaction(cmpny)
Dim sqlInsertT1 As String = ""
Dim sqlInsertT2 As String = ""
For i As Integer = 0 To gv.RowCount - 2
' If gv.Rows(i).Cells(1).Value IsNot System.DBNull.Value AndAlso gv.Rows(i).Cells(1).Value <> "" Then
If (gv.Rows(i).Cells(8).Value = 1) Then
If Not IsDBNull(gv.Rows(i).Cells(1).Value) AndAlso gv.Rows(i).Cells(1).Value.ToString.Length <> 0 Then
Dim cnt As Integer = RecordPresent("CompanyMaster_tbl", "CompanyName", gv.Rows(i).Cells(1).Value)
If cnt = 0 Then
sqlInsertT1 = "Insert Into CompanyMaster_tbl(CompanyName) Values ('" + myTI.ToTitleCase(gv.Rows(i).Cells(1).Value) + "')"
Exetransaction(sqlInsertT1)
Ccid = RecordID("Cid", "CompanyMaster_tbl", "CompanyName", gv.Rows(i).Cells(1).Value)
Else
Ccid = RecordID("Cid", "CompanyMaster_tbl", "CompanyName", gv.Rows(i).Cells(1).Value)
End If
End If
If Not IsDBNull(gv.Rows(i).Cells(3).Value) AndAlso gv.Rows(i).Cells(3).Value.ToString.Length <> 0 Then
sqlInsertT2 = "Insert Into DepartmentMaster_tbl(dtname,dtphone,dtEmail,Cid) Values ('" + myTI.ToTitleCase(gv.Rows(i).Cells(3).Value) + "','" + gv.Rows(i).Cells(4).Value + "','" + gv.Rows(i).Cells(5).Value + "'," & Ccid & ");"
Exetransaction(sqlInsertT2)
Dim departmnt As String = gv.Rows(i).Cells(3).Value
Dim departid As Integer = RecordID("dtId", "DepartmentMaster_tbl", "dtName", departmnt)
Dim sql As String
'----------------------------------
Dim image As Image = TryCast(gv.Rows(i).Cells(6).Value, Image)
If image IsNot Nothing Then
Dim ms As New MemoryStream()
image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif)
Dim imagedata As Byte() = ms.ToArray()
sql = "update DepartmentMaster_tbl set empimage=#photo where dtId='" & departid & "'"
Dim cmd As New SqlCommand(sql, con.connect)
cmd.Parameters.Add("#photo", SqlDbType.Image)
cmd.Parameters("#photo").Value = imagedata
cmd.ExecuteNonQuery()
con.disconnect()
End If
End If
End If
Next
' refreshgrid()
End Sub

Related

Find and highlight the max value in from multiple column in VB.net

Hi i need anyone to help me,
I need to highlight the highest value from multiple column in table
For Ex:-
I have try out some coding..
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
UIUtility = New UIUtility()
Dim dtStartProcessTime As DateTime
Dim dtEndProcessTime As DateTime
Dim dtStartQueryTime As DateTime
Dim dtEndQueryTime As DateTime
Dim tsQueryTime As TimeSpan
Dim tsProcessTime As TimeSpan
Dim strCassList As String = ""
Dim dtDefectInfo As New DataTable
Dim dtDefectList As New DataTable
Dim dtResult As New DataTable
Dim dtSelectDefectInfo As New DataTable
Dim strCass_id As String = ""
Dim dtDisplay As New DataTable
Try
dtStartProcessTime = Now
Me.Title = "Shipping Cassettes List"
Dim sEvent_date As String = Request.QueryString("Event_date").Trim()
Dim sRecipe As String = Request.QueryString("recipe").Trim()
Dim sOperation As String = Request.QueryString("operation").Trim()
Dim sEquipment As String = Request.QueryString("equipment").Trim()
lblStatus.Text = "Event_date:" + sEvent_date + _
"<br>Recipe:" + sRecipe + _
"<br>Operation:" + sOperation + _
"<br>Equipment:" + sEquipment + _
"<br><br>"
Dim dtCass As DataTable
Dim drNew As DataRow
Dim SelectDefectInfo As DataRow()
dtStartQueryTime = Now
dtCass = UIUtility.RetrieveShipCassette(sEvent_date, sRecipe, sOperation, sEquipment)
If dtCass.Rows.Count > 0 Then
strCassList = UIUtility.ReturnStringFromdt(dtCass, "shipping_cass_id")
dtDefectInfo = UIUtility.RetrieveDefectInfo(strCassList)
dtDefectList = UIUtility.dtView(dtDefectInfo, "defect")
dtResult.Columns.Add("cass_id", Type.GetType("System.String"))
For i = 0 To dtDefectList.Rows.Count - 1
If Not (dtDefectList.Rows(i).Item("defect").ToString().Equals("NON")) Then
dtResult.Columns.Add(dtDefectList.Rows(i).Item("defect"), Type.GetType("System.Int32")).DefaultValue = 0
End If
Next
For i = 0 To dtCass.Rows.Count - 1
drNew = dtResult.NewRow
strCass_id = dtCass.Rows(i).Item("shipping_cass_id")
drNew("cass_id") = dtCass.Rows(i).Item("cass_id")
SelectDefectInfo = dtDefectInfo.Select("dest_cass_id = '" + strCass_id + "'")
dtSelectDefectInfo = New DataTable
If SelectDefectInfo.Count > 0 Then
dtSelectDefectInfo = SelectDefectInfo.CopyToDataTable
For j = 0 To dtSelectDefectInfo.Rows.Count - 1
If Not (dtSelectDefectInfo.Rows(j).Item("defect").ToString().Trim().Equals("NON")) Then
drNew(dtSelectDefectInfo.Rows(j).Item("defect").ToString()) = dtSelectDefectInfo.Rows(j).Item("defect_count").ToString()
End If
Next
End If
dtResult.Rows.Add(drNew)
Next
End If
dtEndQueryTime = Now
tsQueryTime = dtEndQueryTime.Subtract(dtStartQueryTime)
'For i As Integer = 0 To dtCass.Rows.Count - 1
' drDisplay = dtDisplay.NewRow
' drDisplay("cass_id") = dtCass.Rows(i)("cass_id").ToString()
' dtDisplay.Rows.Add(drDisplay)
' 'dtCass.Rows(i).Item(
'Next
'e.Row.BorderWidth = 2
dgSummary.DataSource = Nothing
dgSummary.DataSource = dtResult
dgSummary.DataBind()
lblStatus.Text += "Total " + dtResult.Rows.Count.ToString + " rows of data found."
dtEndProcessTime = Now
tsProcessTime = dtEndProcessTime.Subtract(dtStartProcessTime)
lblProcessingTime.Text = "Processing Time: " + tsProcessTime.TotalSeconds.ToString + " Secs (Query Time: " + tsQueryTime.TotalSeconds.ToString + " Secs)"
For Each r As GridViewRow In dtResult.Rows()
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Text, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Text = max Then
r.Cells(i).BackColor = Drawing.Color.Orange
Exit For
End If
Next
Next
Catch ex As Exception
lblMessage.Text = "An error occured:" + ex.Message + " Please contact your administrator."
MyLog.WriteToLog(Me.GetType().Name(), System.Reflection.MethodInfo.GetCurrentMethod().Name, "Exception occured." & vbCrLf & "Error Message:" & ex.Message & vbCrLf & " StackTrace:" & ex.StackTrace)
End Try
End Sub
Protected Sub dgSummary_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgSummary.RowDataBound
Dim cass_id As String = ""
'Dim dtResult As New DataTable
'Dim DataGridView1 As New DataTable
Dim dtCass As New DataTable
If e.Row.RowType = DataControlRowType.DataRow Then
cass_id = e.Row.Cells(0).Text.Trim
If Not e.Row.Cells(0).Text.Trim.Equals("") Then
e.Row.Cells(0).Attributes.Add("Title", "Click and view the cassette details")
e.Row.Cells(0).Attributes("onmouseover") = "this.style.color='DodgerBlue';this.style.cursor='hand';"
e.Row.Cells(0).Attributes("onmouseout") = "this.style.color='Black';"
e.Row.Cells(0).Attributes("onClick") = _
String.Format("window.open('{0}','_blank','scrollbars=yes,status=yes,location=yes,toolbar=yes,menubar=yes,resizable=Yes')", _
ResolveUrl(System.Configuration.ConfigurationManager.AppSettings("SFEHReportLink_SSL") + cass_id))
e.Row.Cells(0).Style("cursor") = "pointer"
End If
End Sub
Maybe theres any coding that more easier than this since i have 17items
Thank you so much for you guys help.
After i add the new code, i got this error,
new error
maybe this example can help you
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
For Each r As DataGridViewRow In DataGridView1.Rows
Dim max As Integer = Integer.MinValue
For i = 1 To r.Cells.Count - 1
Dim n As Integer
If Integer.TryParse(CType(r.Cells(i).Value, String), n) Then max = Math.Max(n, max)
Next
For i = 1 To r.Cells.Count - 1
If r.Cells(i).Value = max Then
r.Cells(i).Style.BackColor = Color.Orange
Exit For
End If
Next
Next
End Sub

asp.net vb Button.click insert to sql working at client but not working when move to server

This code is working a PC. I have filled grid view with the dataset, so I suppose I can read Excel.
However, the insert to sql part is not working when I copy the code to the server and I don't know why. It is not throwing any errors.
I removed the try catch lines but still, there are no errors.
I am adding new code block, I did a test and wrote a siple insert code like;
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = "Data Source=SRV01;Initial Catalog=TR_Development;Persist Security Info=True;User ID=sa"
Dim command As String = "insert into gez_test (test) values ('c')"
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
mysqlcommand.ExecuteNonQuery()
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End Sub
And at server it is not inserting. What can be the problem any idea?
Orginal code
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim path_ As String = "\\exchange\COMPANY\web\" + FileUpload1.FileName
FileUpload1.PostedFile.SaveAs(path_)
Dim identifier As Boolean = False
Dim connStr As String = "provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + path_ + "';Extended Properties=Excel 12.0;"
Dim MyConnection As OleDbConnection
Dim ds As DataSet
Dim MyCommand As OleDbDataAdapter
MyConnection = New OleDbConnection(connStr)
MyConnection.Open()
Dim dtSheets As DataTable = MyConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
Dim listSheet As New List(Of String)
Dim drSheet As DataRow
For Each drSheet In dtSheets.Rows
listSheet.Add(drSheet("TABLE_NAME").ToString())
Next
For Each sheet As String In listSheet
If sheet = "'BAS+Surcharges$'" Then
identifier = True
Exit For
End If
Next
If identifier = True Then
MyCommand = New OleDbDataAdapter("select * from [BAS+Surcharges$]", MyConnection)
ds = New System.Data.DataSet()
MyCommand.Fill(ds)
MyConnection.Close()
'**************SQL***************
Dim line, columns As Integer
line = ds.Tables(0).Rows.Count
columns = ds.Tables(0).Columns.Count
Label1.Text = line.ToString
ASPxTextBox1.Text = line.ToString
If line > 0 And columns = 16 Then
Dim command As String = "exec SP_INTRA_EXCEL_LINE_INSERT" _
+ " #line_isim, #nereden, #via, #nereye, #transit_sure, #baslangic_tarihi," _
+ "#e_kadar_gecerli, #kalem_kodu, #fiyatlandirma, #20DRY, #40DRY, #40HDRY," _
+ "#40HREF_NOR, #kayit_eden"
Dim mysql_connection As New SqlConnection
mysql_connection.ConnectionString = ConfigurationManager.ConnectionStrings("TR_DevelopmentConnectionString").ConnectionString
Dim mysqlcommand As New SqlCommand
mysqlcommand.CommandType = CommandType.Text
mysqlcommand.CommandText = command
mysqlcommand.Connection = mysql_connection
Dim line_isim, nereden, via, nereye, transit_sure, baslangic_tarihi, e_kadar_gecerli,
kalem_kodu, fiyatlandirma, _20DRY, _40DRY, _40HDRY,
_40HREF_NOR, kayit_eden As String
If mysql_connection.State = ConnectionState.Closed Then mysql_connection.Open()
For i = 6 To line - 1
line_isim = ds.Tables(0).Rows(i).Item(13).ToString
nereden = ds.Tables(0).Rows(i).Item(0).ToString
via = ds.Tables(0).Rows(i).Item(14).ToString
nereye = ds.Tables(0).Rows(i).Item(1).ToString
transit_sure = ds.Tables(0).Rows(i).Item(15).ToString
baslangic_tarihi = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(2).ToString).ToString
e_kadar_gecerli = Convert.ToDateTime(ds.Tables(0).Rows(i).Item(3).ToString).ToString
kalem_kodu = ds.Tables(0).Rows(i).Item(7).ToString
fiyatlandirma = ds.Tables(0).Rows(i).Item(8).ToString
_20DRY = ds.Tables(0).Rows(i).Item(9).ToString
_40DRY = ds.Tables(0).Rows(i).Item(10).ToString
_40HDRY = ds.Tables(0).Rows(i).Item(11).ToString
_40HREF_NOR = ds.Tables(0).Rows(i).Item(12).ToString
kayit_eden = Environment.UserName.ToString
mysqlcommand.Parameters.AddWithValue("#line_isim", line_isim)
mysqlcommand.Parameters.AddWithValue("#nereden", nereden)
mysqlcommand.Parameters.AddWithValue("#via", via)
mysqlcommand.Parameters.AddWithValue("#nereye", nereye)
mysqlcommand.Parameters.AddWithValue("#transit_sure", transit_sure)
mysqlcommand.Parameters.AddWithValue("#baslangic_tarihi", baslangic_tarihi)
mysqlcommand.Parameters.AddWithValue("#e_kadar_gecerli", e_kadar_gecerli)
mysqlcommand.Parameters.AddWithValue("#kalem_kodu", kalem_kodu)
mysqlcommand.Parameters.AddWithValue("#fiyatlandirma", fiyatlandirma)
mysqlcommand.Parameters.AddWithValue("#20DRY", _20DRY)
mysqlcommand.Parameters.AddWithValue("#40DRY", _40DRY)
mysqlcommand.Parameters.AddWithValue("#40HDRY", _40HDRY)
mysqlcommand.Parameters.AddWithValue("#40HREF_NOR", _40HREF_NOR)
mysqlcommand.Parameters.AddWithValue("#kayit_eden", kayit_eden)
mysqlcommand.ExecuteNonQuery()
mysqlcommand.Parameters.Clear()
Next
If mysql_connection.State = ConnectionState.Open Then mysql_connection.Close()
End If
End If
ASPxGridView1.DataBind()

how to use componentone c1printdocument in asp.net for reading text file and convert into pdf with format?

I am using the C1PrintDocument class to read a text file and convert into pdf in web. Actually it converts into pdf but without the format as like in text file.
For eg. I have a text file which has only one page. But it makes into two pages while convert into pdf. Below is the code what I use.
Imports System.IO
Imports C1.C1Preview
Imports C1.C1Pdf
Imports C1.Web.Wijmo.Controls.C1ReportViewer
Imports System.Runtime.Serialization.Formatters.Binary
Imports C1.C1Pdf.PdfDocumentInfo
Imports C1.C1Preview.C1PrintDocument
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Handles Me.Load
Try
Dim strmappath As String = System.Web.HttpContext.Current.Server.MapPath("~")
Dim filename As String
filename = Path.Combine(Server.MapPath("~"), "12214.txt")
Dim sr As New System.IO.StreamReader(filename, System.Text.Encoding.UTF8)
Dim str As [String] = sr.ReadToEnd()
Dim doc1 As C1PrintDocument = C1ReportViewer.CreateC1PrintDocument()
Dim doc As New C1PrintDocument
doc.Pages(1).PageSettings.TopMargin = 0
doc.Pages(1).PageSettings.LeftMargin = 0
doc.Pages(1).PageSettings.RightMargin = 0
doc.StartDoc()
Dim overlay As New RenderArea()
overlay.Width = "100%"
overlay.Height = "100%"
overlay.Style.Borders.All = LineDef.Default
doc.PageLayout.Overlay = overlay
Dim lines As String() = System.IO.File.ReadAllLines(filename)
Dim linecnt As Integer = System.IO.File.ReadLines(filename).Count
Dim strpages1 As String()
ReDim strpages1(Math.Abs(linecnt / 66) - 1)
Dim intcnt As Integer
Dim intlinereadcnt As Integer
intlinereadcnt = 0
intcnt = 0
intlinereadcnt = 0
For Each line In lines
If intcnt <= 66 Then
If intcnt <> 66 Then
strpages1(intlinereadcnt) = strpages1(intlinereadcnt) &
line & vbCrLf
End If
intcnt = intcnt + 1
ElseIf intcnt = 67 Then
intlinereadcnt = intlinereadcnt + 1
intcnt = 0
End If
Next
Dim strPages As String() = str.Split(Chr(12))
Dim strPage As String = String.Empty
Dim txtPage As New C1.C1Preview.RenderText(doc)
With doc
.AllowNonReflowableDocs = True
For Each strPage In strpages1
If strPage.Length > 0 Then
txtPage.Text = strPage
txtPage.X = 150
doc.Style.TextColor = Drawing.Color.Blue
.RenderBlockText(txtPage.Text)
.Style.WordWrapMode = False
.NewPage()
End If
Next
End With
Dim m_pdfExporter As C1.C1Preview.Export.PdfExporter
m_pdfExporter = C1.C1Preview.Export.ExportProviders.
PdfExportProvider.NewExporter()
m_pdfExporter.Document = doc
m_pdfExporter.Export(Server.MapPath("~") & "12214" & ".pdf")
Dim sr2 As System.IO.MemoryStream
sr2 = New MemoryStream
doc.Save(sr2)
Dim biteArray As Byte() = New Byte(sr2.Length - 1) {}
sr2.Position = 0
sr2.Read(biteArray, 0, CInt(sr2.Length))
'm_pdfExporter.Export(Path.GetTempPath & "\" & "12214" & ".pdf")
Response.Clear()
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/pdf"
'Response.BinaryWrite(biteArray)
Response.AddHeader("Content-Disposition", "attachment;filename=" & "12214" & ".pdf")
Response.BinaryWrite(System.IO.File.ReadAllBytes(Server.MapPath("~") & "12214" & ".pdf"))
Catch ex As Exception
End Try
End Sub
Try using c1PrintDocument1.Export("filename.pdf", true) instead.
Thanks,
Richa

parameter causes the data unreadable in the form 2 does not appear on the web version of vb.net

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim id As String, sLogon_User As String, sAuth_User As String, sUser_ID As String
Dim sServer_Name As String
Dim sIP_Address As String
sIP_Address = Request.ServerVariables("REMOTE_ADDR")
Dim hit As New PagePosting
Dim currentPosting As Posting = CmsHttpContext.Current.Posting
Dim webContext As WebAuthorContext
webContext = WebAuthorContext.Current
'sNama_Perusahaan = Request.QueryString("sentraID")
'Response.Write("masuk sini dgn nilai = " & CmsHttpContext.Current.CmsQueryString())
sData = ""
If Not Page.IsPostBack Then
'sNama_Perusahaan = Request.ServerVariables("sentraID")
sNama_Perusahaan = Request.QueryString("sentraID")
' sNama_Perusahaan = Request.QueryString("sentraID")
Response.Write("masuk sini dgn nilai = " & Request.QueryString("sentraID") & sNama_Perusahaan)
tampil(sNama_Perusahaan)
End If
Sub tampil(ByVal sParam As String)
Dim rd As SqlDataReader
Dim myConnection = New SqlConnection(ConfigurationSettings.AppSettings("RegBIK"))
myConnection.Open()
Dim adadata As Integer
' Dim myCommand As New SqlCommand("select count (*) from kuesioner where ltrim(rtrim(NmPerush)) ='aaa'", myConnection)
Dim myCommand As New SqlCommand("select count (*) from kuesioner where ltrim(rtrim(NmPerush)) ='&sParam'", myConnection)
rd = myCommand.ExecuteReader
While rd.Read
adadata = rd.GetInt32(0)
End While
myConnection.close()
Try
If adadata > 0 Then
myConnection.Open()
' Dim myCommands As New SqlCommand("select * from kuesioner where ltrim(rtrim(NmPerush)) ='aaa'", myConnection)
Dim myCommands As New SqlCommand("select * from kuesioner where ltrim(rtrim(NmPerush)) ='&sParam'", myConnection)
rd = myCommands.ExecuteReader
While rd.Read
disabledAll()
Me.btnUpload.Enabled = False
Me.btnPreview.Enabled = True
txtNmPerush.Value = rd.GetString(1)
Me.txtNmPemilik.Value = rd.GetString(2)
Me.txtAlmtPerush.Value = rd.GetString(3)
Me.txttlpn.Value = rd.GetString(4)
Me.txtEmail.Value = rd.GetString(5)
Me.txtLamaPerush.Value = rd.GetString(6)
Me.txtJenis.Value = rd.GetString(7)
Me.txtSpesialisasi.Value = rd.GetString(8)
Me.txtkualitas.Value = rd.GetString(9)
Me.txtMerk.Value = rd.GetString(10)
Me.txtStandarPesanan.Value = rd.GetString(11)
Me.txtProduksi.Value = rd.GetString(12)
Me.txtlokal.Value = rd.GetString(13)
Me.txtnasional.Value = rd.GetString(14)
Me.txtekspor.Value = rd.GetString(15)
Me.txtpengalaman.Value = rd.GetString(16)
Me.txtlamaekspor.Value = rd.GetString(17)
Me.txtbiaya.Value = rd.GetString(18)
End While
Else
clearAll()
End If
rd.Close()
myConnection.close()
Catch SQLexc As SqlException
Response.Write("Open Failed. Error Details are: " & SQLexc.ToString())
End Try
End Sub
the source code to get the first parameter, the second to throw codingan parameters to form 2 and the third codingan to read in the form 2..I've tried but still can not
I would think that that code would produce an error, but you did not state that.
To add a parameter to the SQL statement:
Dim myCommand As New SqlCommand("SELECT COUNT(*) FROM kuesioner WHERE LTRIM(RTRIM(NmPerush)) = #param1", myConnection)
myCommand.Parameters.Add(New SqlParameter With {.ParameterName = "param1", _
.SqlDbType = SqlDbType.NVarChar, _
.Size = 200, _
.Value = sParam})
Please alter the .SqlDbType and .Size to match the definition in the database.

Sharepoont 2010 webpart vb.net Listbox SelectIndexChanged and errors

So let start I am new to coding widgets and in general. I had originally coded this in vb for asp pages and it work fine. Now converting over to a SharePoint 2010 webpart (not visual webpart).
The project is List box 1 has the user groups that they manage, List box 2 has the users in said group, List box 3 has all user not in List box 2
I am sure there lots of this that should be fix. Like not putting in admin login to get the data.
But the problem I have is: if select a group it will display the appropriate data but select a second group or select a user to add; same error.
Error:
"Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request."
Also still trying to figure out how to do the button to add a user.
Need some serious help please. I know part of the post back just having a hard time finding resources.
Below is the code:
Imports System
Imports System.ComponentModel
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.WebControls
Imports ActiveDs
Imports System.DirectoryServices
Imports System.Data
Imports ADODB
Imports System.Runtime.InteropServices
<ToolboxItemAttribute(False)> _
Public Class Groups
Inherits System.Web.UI.WebControls.WebParts.WebPart
Private LBgrp As ListBox
Private LBgrpmem As ListBox
Private LBaddgrp As ListBox
Private btnadd As Button
Protected Overrides Sub CreateChildControls()
Me.LBgrpmem = New ListBox
Me.LBgrpmem.AutoPostBack = True
Me.LBgrpmem.DataValueField = "sAMAccountName"
Me.LBgrpmem.DataTextField = "displayName"
Me.LBgrpmem.DataBind()
Me.LBgrpmem.Rows = 8
Me.LBgrpmem.Width = 170
Me.LBgrpmem.Height = 350
Me.LBgrpmem.Items.Insert(0, New ListItem("-- Current Members --"))
Me.Controls.Add(LBgrpmem)
Me.LBaddgrp = New ListBox
Me.LBaddgrp.AutoPostBack = True
Me.LBaddgrp.DataTextField = "displayName"
Me.LBaddgrp.DataValueField = "sAMAccountName"
Me.LBaddgrp.DataBind()
Me.LBaddgrp.Items.Insert(0, New ListItem("-- Add Users --"))
Me.LBaddgrp.Width = 170
Me.LBaddgrp.Height = 350
AddHandler LBaddgrp.SelectedIndexChanged, New EventHandler(AddressOf DLAdd_SelectedIndexChanged)
Me.Controls.Add(LBaddgrp)
Me.btnadd = New Button()
' AddHandler Me.btnadd.Click, New EventHandler(AddressOf Click_btnadd)
Me.btnadd.Text = "Add User"
Me.Controls.Add(btnadd)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
Dim oCon As New ADODB.Connection
Dim oRecordSet As New ADODB.Recordset
Dim oCmd As New ADODB.Command
Dim sFullUser As String = Environment.UserName
Dim sProperties = "name,ADsPath,description,member,memberof,managedObjects"
Dim sGroup = "*"
Dim aMember
Dim iCount
oCon.ToString()
oCmd.ToString()
sFullUser.ToString()
sProperties.ToString()
sDomainADsPath.ToString()
oCon.Provider = "ADsDSOObject"
oCon.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd.ActiveConnection = oCon
oCmd.CommandText = "<" & sDomainADsPath & ">;(&(objectCategory=person)(objectClass=user)(sAMAccountName=" & sFullUser & "));" & sProperties & ";subtree"
oRecordSet = oCmd.Execute
Dim de As DirectoryServices.DirectoryEntry = New DirectoryServices.DirectoryEntry(sDomainADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim i As Integer = 0
Dim sl As SortedList = New SortedList(New CaseInsensitiveComparer)
de.ToString()
While Not oRecordSet.EOF
aMember = oRecordSet.Fields("managedObjects").Value
If Not IsDBNull(aMember) Then
For iCount = 0 To UBound(aMember)
Dim groupDN As String = ("distinguishedName=" & aMember(iCount))
Dim src As DirectoryServices.DirectorySearcher = New DirectoryServices.DirectorySearcher("(&(objectCategory=Group)(" & groupDN & "))")
src.SearchRoot = de
src.SearchScope = DirectoryServices.SearchScope.Subtree
For Each res As DirectoryServices.SearchResult In src.FindAll
sl.Add(res.Properties("name")(0).ToString, i)
i += 1
Next
Next
End If
oRecordSet.MoveNext()
End While
Me.LBgrp = New ListBox
Me.LBgrp.AutoPostBack = True
Me.LBgrp.DataSource = sl
Me.LBgrp.DataTextField = "key"
Me.LBgrp.DataValueField = "value"
Me.LBgrp.DataBind()
Me.LBgrp.Items.Insert(0, New ListItem("-- Groups --"))
Me.Controls.Add(LBgrp)
Me.LBgrp.SelectedIndex = 0
AddHandler LBgrp.SelectedIndexChanged, New EventHandler(AddressOf LBgrp_SelectedIndexChanged)
LBgrp.SelectedItem.ToString()
End Sub
Protected Sub LBgrp_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles LBgrp.SelectedIndexChanged
Dim strQuery As String = "" & LBgrp.SelectedItem.Text.ToString() & "'"
'LBgrpmem.Items.Clear()
Dim oRootDSE2 = GetObject("LDAP://RootDSE")
Dim sDomainADsPath2 = "LDAP://" & oRootDSE2.Get("defaultNamingContext")
Dim oCon2 As New ADODB.Connection
Dim oRecordSet2 As New ADODB.Recordset
Dim sFullUser2 As String = Environment.UserName
Dim oCmd2 As New ADODB.Command
Dim sProperties2 = "name,ADsPath,description,member,memberof,managedObjects"
Dim grpADsPath2
Dim grpdsplynm2
oRootDSE2 = Nothing
oCon2.Provider = "ADsDSOObject"
oCon2.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd2.ActiveConnection = oCon2
oCmd2.CommandText = "<" & sDomainADsPath2 & ">;(&(objectCategory=group)(objectClass=group)(CN=" & LBgrp.SelectedItem.Text & "));" & sProperties2 & ";subtree"
oRecordSet2 = oCmd2.Execute
While oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
grpADsPath2.ToString()
grpdsplynm2 = grpADsPath2.remove(0, 7)
grpdsplynm2.ToString()
oRecordSet2.MoveNext()
End While
While Not oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
grpADsPath2.ToString()
grpdsplynm2 = grpADsPath2.remove(0, 7)
grpdsplynm2.ToString()
oRecordSet2.MoveNext()
End While
Dim groupDN2 As String = "" & grpdsplynm2 & ""
Dim filter As String = [String].Format("(&(objectClass=user)(objectCategory=person)(memberOf={0}))", groupDN2)
Me.LBgrpmem.AutoPostBack = True
Me.LBgrpmem.DataSource = FindUsers(filter, New String() {"sAMAccountName", "displayName"}, sDomainADsPath2, True)
Me.LBgrpmem.DataValueField = "sAMAccountName"
Me.LBgrpmem.DataTextField = "displayName"
Me.LBgrpmem.DataBind()
Me.LBgrpmem.Items.Insert(0, New ListItem("-- Current Members --"))
Me.Controls.Add(LBgrpmem)
Dim usrDN As String = "" & grpdsplynm2 & ""
usrDN.ToString()
Dim usrfilter As String = [String].Format("(&(objectClass=user)(objectCategory=person)(!memberOf={0}))", groupDN2)
Me.LBaddgrp.AutoPostBack = True
Me.LBaddgrp.DataSource = FindUsers(usrfilter, New String() {"sAMAccountName", "displayName"}, sDomainADsPath2, True)
Me.LBaddgrp.DataTextField = "displayName"
Me.LBaddgrp.DataValueField = "sAMAccountName"
Me.LBaddgrp.DataBind()
Me.LBaddgrp.Items.Insert(0, New ListItem("-- Add Users --"))
'AddHandler LBaddgrp.SelectedIndexChanged, New EventHandler(AddressOf DLAdd_SelectedIndexChanged)
Me.Controls.Add(LBaddgrp)
End Sub
Public Function FindUsers(ByVal sFilter As String, ByVal columns() As String, ByVal path As String, ByVal useCached As Boolean) As Data.DataSet
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
'try to retrieve from cache first
Dim context As HttpContext = HttpContext.Current
Dim userDS As Data.DataSet = CType(context.Cache(sFilter), Data.DataSet)
If userDS Is Nothing Or Not useCached Then
'setup the searching entries
Dim deParent As New DirectoryServices.DirectoryEntry(sDomainADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim ds As New DirectoryServices.DirectorySearcher(deParent, sFilter, columns, DirectoryServices.SearchScope.Subtree)
ds.PageSize = 1000
ds.Sort.PropertyName = "displayName" 'sort option
Using (deParent)
userDS = New Data.DataSet("userDS")
Dim dt As Data.DataTable = userDS.Tables.Add("users")
Dim dr As Data.DataRow
'add each parameter as a column
Dim prop As String
For Each prop In columns
dt.Columns.Add(prop, GetType(String))
Next prop
Dim src As DirectoryServices.SearchResultCollection = ds.FindAll
Try
Dim sr As DirectoryServices.SearchResult
For Each sr In src
dr = dt.NewRow()
For Each prop In columns
If sr.Properties.Contains(prop) Then
dr(prop) = sr.Properties(prop)(0)
End If
Next prop
dt.Rows.Add(dr)
Next sr
Finally
src.Dispose()
End Try
End Using
'cache it for later, with sliding window
context.Cache.Insert(sFilter, userDS, Nothing, DateTime.MaxValue, TimeSpan.FromSeconds(10))
End If
Return userDS
End Function 'FindUsers
Protected Sub DLAdd_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) 'Handles Click_btnadd
Dim oRootDSE = GetObject("LDAP://RootDSE")
Dim sDomainADsPath = "LDAP://" & oRootDSE.Get("defaultNamingContext")
Dim oCon As New ADODB.Connection
Dim oRecordSet As New ADODB.Recordset
Dim oRcrdSet As New ADODB.Recordset
Dim oCmd As New ADODB.Command
Dim oCmd1 As New ADODB.Command
Dim sGroup = "*"
Dim sProperties = "name,ADsPath,description,member,memberof,proxyAddresses"
Dim grpADsPath
Dim grpdsplynm
Dim addusrADsPath
Dim addusrname
oRootDSE = Nothing
oCon.Provider = "ADsDSOObject"
oCon.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd.ActiveConnection = oCon
oCmd1.ActiveConnection = oCon
oCmd.CommandText = "<" & sDomainADsPath & ">;(&(objectClass=group)(cn=" & LBgrp.SelectedItem.Text & "));" & sProperties & ";subtree"
oRecordSet = oCmd.Execute
'Group Query
While Not oRecordSet.EOF
grpADsPath = oRecordSet.Fields("ADsPath").Value
grpdsplynm = oRecordSet.Fields("name").Value
oRecordSet.MoveNext()
End While
oCmd1.CommandText = "<" & sDomainADsPath & ">;(&(objectCategory=person)(objectClass=user)(cn=" & LBaddgrp.SelectedItem.Text & "));" & sProperties & ";subtree"
oRcrdSet = oCmd1.Execute
'User query
While Not oRcrdSet.EOF
addusrADsPath = oRcrdSet.Fields("ADsPath").Value
addusrname = oRcrdSet.Fields("name").Value
oRcrdSet.MoveNext()
End While
' Bind directly to the group
'
Dim oRootDSE2 = GetObject("LDAP://RootDSE")
Dim sDomainADsPath2 = "LDAP://" & oRootDSE2.Get("defaultNamingContext")
Dim oCon2 As New ADODB.Connection
Dim oRecordSet2 As New ADODB.Recordset
Dim sFullUser2 As String = Environment.UserName
'Dim sFullUser2 = Request.ServerVariables("LOGON_USER")
'Dim sUser2 = Split(sFullUser2, "\", -1)
Dim oCmd2 As New ADODB.Command
Dim sProperties2 = "name,ADsPath,description,member,memberof,managedObjects"
Dim grpADsPath2
oRootDSE2 = Nothing
oCon2.Provider = "ADsDSOObject"
oCon2.Open("ADProvider", "ADMINUSER#Domain.com", "ADMINPASSWORD")
oCmd2.ActiveConnection = oCon2
oCmd2.CommandText = "<" & sDomainADsPath2 & ">;(&(objectCategory=group)(objectClass=group)(CN=" & LBgrp.SelectedItem.Text & "));" & sProperties2 & ";subtree"
oRecordSet2 = oCmd2.Execute
While Not oRecordSet2.EOF
grpADsPath2 = oRecordSet2.Fields("ADsPath").Value
oRecordSet2.MoveNext()
End While
Dim group As New DirectoryServices.DirectoryEntry("" & grpADsPath2 & "", "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim user As New DirectoryServices.DirectoryEntry(addusrADsPath, "ADMINUSER#Domain.com", "ADMINPASSWORD", DirectoryServices.AuthenticationTypes.Secure)
Dim isMember As Boolean = Convert.ToBoolean(group.Invoke("IsMember", New Object() {user.Path}))
If isMember Then
'
' TO CREATE ERROR MESSAGE
Else
' Add the user to the group by invoking the Add method
'
group.Invoke("Add", New Object() {user.Path})
End If
If Not IsNothing(user) Then
user.Dispose()
End If
If Not IsNothing(group) Then
group.Dispose()
End If
Console.ReadLine()
If (Err.Number <> 0) Then
' TO CREATE ERROR MESSAGE
Else
' TO CREATE SUCCESS MESSAGE
End If
End Sub
Protected Overrides Sub Render(writer As System.Web.UI.HtmlTextWriter)
LBgrp.RenderControl(writer)
LBgrpmem.RenderControl(writer)
LBaddgrp.RenderControl(writer)
btnadd.RenderControl(writer)
End Sub
End Class
if memory serves me correctly, Page_Load event is firing on a postback too, where you are trying to create another instance of your drop down. So the system is trying to recreate the state of ListBox from ViewState but it is not the same ListBox, because you have just recreated it. So it barks.
To avoid it, in the page_load only create "parent" drop down if it's not postback. i.e.
Begin Page_Load()
If !Page.IsPostBack() Then
'load code here
End If
End Page_Load
Also there's no need to write
Me.LBgrpmem = New ListBox
as it is already created. Changing the datasource is usually enuff.