I have a div where it's property set runat="server" with its ID. I'm trying to put dynamic background image for that particular div from MySQL database where it's path url mentioned in row. Now all working fine but I don't know how to give style affect to that particular div only. Currently I defined only on div which results to get background image in all div on that page. How can I define that div class or ID in my code?
Private Sub coverContent_Init(sender As Object, e As EventArgs) Handles coverContent.Init
Try
Dim css As New HtmlGenericControl()
css.TagName = "style"
css.Attributes.Add("type", "text/css")
Dim imageURL As String = String.Empty
Dim var3 As String
var3 = Request.QueryString("hospitalID")
Dim str As String = "Select hospitalID, coverImage from hospitals where hospitalID='" + var3 + "';"
con.Open()
Dim cmd As New MySqlCommand(str, con)
Dim da As New MySqlDataAdapter(cmd)
Dim dt As New DataTable
da.Fill(dt)
con.Close()
If dt.Rows.Count > 0 Then
generalID.Text = dt.Rows(0)("hospitalID").ToString
imageURL = dt.Rows(0)("coverImage").ToString
End If
con.Close()
css.InnerHtml = (Convert.ToString("div{background-image: url(") & imageURL) + ");}"
Page.Header.Controls.Add(css)
MyBase.OnInit(e)
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Very simple where you have mentioned div there you need to specify class of div where you want to show background image. Like below
css.InnerHtml = (Convert.ToString(".divClassName{background-image: url(") & imageURL) + ");}"
Related
i want to display mysql data base from the dropdownlist. i populate data from dropdownlist using this code and it works perfectly. in this code it will show the productnames in the dropdownlist
If Not Me.IsPostBack Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New MySqlConnection(constr)
Using cmd As New MySqlCommand("SELECT tbl_productid,tbl_productname FROM tbl_products")
cmd.CommandType = CommandType.Text
cmd.Connection = con
con.Open()
cmbProducts.DataSource = cmd.ExecuteReader()
cmbProducts.DataTextField = "tbl_productname"
cmbProducts.DataValueField = "tbl_productid"
cmbProducts.DataBind()
con.Close()
End Using
End Using
cmbProducts.Items.Insert(0, New ListItem("Select Product"))
End If
Now base from the selected product name i want to display its productID to textbox. but this code gives me no output? i dont know what is wrong with my code anyone who can help me
This is code
Protected Sub cmbProducts_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cmbProducts.SelectedIndexChanged
'MsgBox("Hellow World!", MsgBoxStyle.Critical)
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim con As New MySqlConnection(constr)
con.Open()
Dim cmd As New MySqlCommand("SELECT tbl_productid from tbl_products where tbl_productname = '" + cmbProducts.Text + "'", con)
Dim sda As New MySqlDataAdapter(cmd)
'Dim dr As New MySqlDataReader
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.Read Then
txtProductID.Text = dr.GetValue(0)
End If
con.Close()
con.Dispose()
End Sub
Ok, a few things.
The drop list has two columns. data value (id), and data text.
What you have looks good.
However, when you get/grab/use the drop list, then you have this:
DropDownList1.Text - this will return the data value (1st column)
DropDownList1.SelectedValue - this will ALSO return data value (1st column)
DropDownList1.SelectedItem.Text - this gets the 2nd display text value (2nd column)
So, because a LOT of drop lists can be only one column, then the .text and .SelectedValue can both be used. (in other words, you can use .text, but it gets the first value, and since a lot of drop lists might only have one column, then .text always gets that first value). But I would consider the habit of SelectedValue for the column that drives the drop list.
In your case, you really do want the 2nd column, and thus you want to use:
DropDownList1.SelectedItem.Text
So,
New MySqlCommand("SELECT tbl_productid from tbl_products where tbl_productname = '"
+ cmbProducts.SelectedItem.Text + "'", con)
I used my own data to demonstrate. Also I used given control names in my test program. This is not what your want to do in your application. Your control names are good.
I broke the code into the data access part and the user interface code. There is very little code in the actual event procedure.
You have set the .DataValueField to the id so you can retrieve that value in the SelectedIndexChanged event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
FillDropDownList()
End If
End Sub
Private Sub FillDropDownList()
Dim dt = GetListBoxData()
DropDownList1.DataTextField = "Name"
DropDownList1.DataValueField = "ID"
DropDownList1.DataSource = dt
DropDownList1.DataBind()
End Sub
Private Function GetListBoxData() As DataTable
Dim dt = New DataTable
Dim Query = "Select Top 10 ID, Name
FROM Coffees;"
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand(Query, cn)
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
TextBox1.Text = DropDownList1.SelectedValue
End Sub
There is no need to make a second round trip to the database. You already have the data you require.
Application Screen Shot
I tried searching all over from the internet if this kind of thing is possible but I didn't find any that solve my problem..
Here is my code for ... but this code keep on adding another usercontrols to my panel...
Sub sorbyID()
pnList.Controls.Clear()
connect()
Dim dr As MySqlDataReader
Dim str As String = "SELECT * FROM clientinfo order by id desc"
Dim cmd As New MySqlCommand(str, con)
dr = cmd.ExecuteReader
For i As Integer = 0 To 10
Dim c As Control1 = New Control1
If dr.Read Then
c.Dock = DockStyle.Top
c.lblID.Text = dr("ID")
c.lblName.Text = dr("lname") & ", " & dr("fName")
c.lblPlan.Text = dr("plan")
c.lblIPadd.Text = dr("ipAdd")
c.lblMac.Text = dr("Mac")
c.lblBrgy.Text = dr("brgy")
pnList.Controls.Add(c)
End If
Next
End Sub
I want to put sum of each month in a label in the table from MySQL database but i dont know to make it in the label cz i have lbl1, lbl2, ... lbl12.
My code:
connection.Open()
query = " SELECT SUM(Amount_income_table), MONTHNAME(Date_income_table)
FROM bacci.income_table
where year(Date_income_table)='" & LblYear.Text & "'
GROUP BY MONTHNAME(Date_income_table);"
Comand = New MySqlCommand(query, connection)
READER = Comand.ExecuteReader
While READER.Read
ChartIncomeYear.Series("Incomes").Points.AddXY(READER.GetString("MONTHNAME(Date_income_table)"), READER.GetString("SUM(Amount_income_table)"))
End While
connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
this code will fill the chart but i also want to fill the labels with the same query.
you shouldn't have your label as lbl1, lbl2 and lbl3 etc. You should create them at run time. Try this code i a blank project. Adapt your code from this example. I like using list of objects but you can use an array too
Dim LabelList As List(Of Label)
Sub LoadSumLabel()
LabelList = New List(Of Label)
For x = 1 To 12
Dim NewLabel As New Label
With NewLabel
.Name = DateAndTime.MonthName(x)
.Text = "0"
.AutoSize = True
.Left = 10
.Top = 10 + (LabelList.Count * NewLabel.Height)
End With
LabelList.Add(NewLabel)
Me.Controls.Add(LabelList.Item(LabelList.Count - 1))
AddHandler LabelList.Item(LabelList.Count - 1).Click, AddressOf Label_Click
'you can create a panel and add you control to it the same way. So if you resize the form you can have the scroll bars if it doesnt fit
'somepanel.controls(LabelList.Item(LabelList.Count - 1))
Next
End Sub
Private Sub Label_Click(sender As Object, e As EventArgs)
Dim thisLabel As Label = DirectCast(sender, Label)
MsgBox(thisLabel.Name, vbOKOnly, "Result")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
LoadSumLabel()
End Sub
Sub RunQuery()
connection.Open()
query = " SELECT SUM(Amount_income_table), MONTHNAME(Date_income_table)
FROM bacci.income_table
where year(Date_income_table)='" & LblYear.Text & "'
GROUP BY MONTHNAME(Date_income_table);"
Comand = New MySqlCommand(query, connection)
READER = Comand.ExecuteReader
While READER.Read
ChartIncomeYear.Series("Incomes").Points.AddXY(READER.GetString("MONTHNAME(Date_income_table)"), READER.GetString("SUM(Amount_income_table)"))
LabelList.Find(Function(lb As Label) lb.Name = READER.GetString("MONTHNAME(Date_income_table)")).Text = READER.GetString("SUM(Amount_income_table)")
End While
connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
End Sub
Name your labels like this lblJanuary, lblFebruary, lblMarch .... lblDecember. And then you can easily solve your problem using this code :
query = " SELECT SUM(Amount_income_table) as Total, MONTHNAME(Date_income_table)
FROM bacci.income_table
where year(Date_income_table)='" & LblYear.Text & "'
GROUP BY MONTHNAME(Date_income_table);"
Comand = New MySqlCommand(query, connection)
READER = Comand.ExecuteReader
While READER.Read
ChartIncomeYear.Series("Incomes").Points.AddXY(READER.GetString("MONTHNAME(Date_income_table)"), READER.GetString("SUM(Amount_income_table)"))
Me.Controls("lbl" & READER.GetString("MONTHNAME(Date_income_table)")).Text = READER.GetString("Total")
End While
connection.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
connection.Dispose()
End Try
I have a form with two datagridview that gets items from a mysql database.
My goal is to click an item of the first DGV and get it inserted into the second, then (pressing a button) update the table on the database.
The problem is that I cannot add a row (I get exception: Can not add rows programmatically to the set of rows in DataGridView when data-bound control) and, if I programmatically fill the last row (the row for manual inserting) the value is not acquired.
But if I fill manually the last row and press the "update button" the database become updated.
This is the code of "CellContentClick"
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim DvgRow% = e.RowIndex
Dim DvgCol% = e.ColumnIndex
Dim SelCell$ = Me.DataGridView1.Item(DvgCol, DvgRow).Value.ToString.Trim()
Dim IntColSel$ = Me.DataGridView1.Columns(DvgCol).HeaderText
Dim Dgv2Rows% = Me.DataGridView2.RowCount
If IntColSel.ToUpper = "REGION" Then
'Here I get the value in the last row but is ignored being updated
Me.DataGridView2.Item(0, Me.DataGridView2.RowCount - 1).Value = SelCell
'Here I get exception
Me.DataGridView2.Rows.Add()
End If
End Sub
This is the code to fill the 2nd DGV:
Private Sub GetInDGV2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button13.Click
With DataGridView2
.DataSource = Nothing
.Rows.Clear()
.Columns.Clear()
End With
cnString = "datasource=" + Server_Name + ";username= " + UserDB + _
";password=" + Password + ";database=" + Database_Name + ""
sqlQRY2 = "Select Region from regions"
conn = New MySqlConnection(cnString)
Try
conn.Open()
da2 = New MySqlDataAdapter(sqlQRY2, conn)
Dim cb2 As MySqlCommandBuilder = New MySqlCommandBuilder(da2)
da2.Fill(ds2, "regions")
DataGridView2.DataSource = ds2
DataGridView2.DataMember = "regions"
Catch ex As Common.DbException
MsgBox(ex.ToString)
Finally
conn.Close()
End Try
End Sub
I saw this question aswered but I wasn't able to translate from C an test it.
Thanks for any help.
As DataGridview2 is bounded to a DataTable2, you cannot directly modify the cells. You must update DataTable2 by adding a new DataRow. Once added, DataGRidView2 will be automatically refreshed.
To get the RowValues required to populate your new DataRow, you may access to DataTable1 DataRow. To Get the DataRow of underlying DataTable1, corresponding to the current row of dataGridView1:
Dim selectedrow As DataRow = DirectCast(DataGridView1.CurrentRow.DataBoundItem, DataRowView).Row ;
Then create a new DataRow in DataTable2 with the values got from slectedrow.
Dim dataTable2 As DataTable = ds2("Regions")
Dim newrow As DataRow = dataTable2.NewRow()
For i As Integer = 0 To selectedrow.Count - 1
newrow(i) = selectedrow(i)
Next
dataTable2.Rows.Add(newrow)
when i try to select an item in the ListView that has no image in my database this error shows Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. i tried to put up some code like isDBNull or DBNull but it's applicable.
here's my code:
Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "server = localhost; user id = root; database = db; password = root"
Dim Sql As String = "select * from candidate where idn='" & LvPeople.SelectedItems(0).Text & "'"
Dim conn As New MySqlConnection(connstring)
Dim cmd As New MySqlCommand(Sql, conn)
Dim dr As MySqlDataReader = Nothing
conn.Open()
dr = cmd.ExecuteReader()
dr.Read()
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
conn.Close()
End If
End Sub
End Class
the error points here:
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
i really have no idea what to put here. just a newbie here.
Since it is possible that there is no image data previously saved for a row, you need to test for DBNull before trying to use it:
If IsDBNull(dr("photo")) = False Then
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
Else
' maybe display a "no Photo Available" stock image
End If
Note that this DBNull test is different than the one Steve is using. IsDBNull is a language function while the one he is using is a method of the DataReader object, which is also why there are different requirements. Yet a third way would be to compare it to System.DbNull:
If DBNull.Value.Equals(dr("photo")) = False Then
...
End If
Use the DataReader method IsDBNull, but this method requires the position of the field in the IDataRecord used by the reader, so you need to call also GetOrdinal with the name of the field to check
(Links point to the Sql Server version but they are the same for MySql)
Private Sub LvPeople_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LvPeople.SelectedIndexChanged
If LvPeople.SelectedItems.Count > 0 Then
Dim connstring As String = "...."
Dim Sql As String = "select * from candidate where idn=#id"
Using conn = new MySqlConnection(connstring)
Using cmd = new MySqlCommand(Sql, conn)
conn.Open()
cmd.Parameters.AddWithValue("#id", LvPeople.SelectedItems(0).Text)
Using dr = cmd.ExecuteReader()
if dr.Read() Then
if Not dr.IsDbNull(dr.GetOrdinal("photo")) Then
Dim imagebytes As Byte() = CType(dr("photo"), Byte())
Using ms As New IO.MemoryStream(imagebytes)
PictureBox1.Image = Image.FromStream(ms)
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Using
End If
End If
End Using
End Using
End Using
End If
End Sub