Yes, but the sheet names must be known to hardcode a range.
Also, will there ever be any discontinuities (empty cells) is the column data. This is not a problem, it needs to be accounted for in computing the range to process.
Yes, but the sheet names must be known to hardcode a range.
Also, will there ever be any discontinuities (empty cells) is the column data. This is not a problem, it needs to be accounted for in computing the range to process.
Probably an empty cell.
try: if Not String.IsNullOrEmpty(DataGridView1.Rows(i).Cells(4).Value.ToString()) Then tot += Convert.ToDouble(DataGridView1.Rows(i).Cells(4).Value)
Would be possible to have a new category added to Software Development for MS Office macros (VBA)?
Right now these types of questions often get asked in the VB.Net forum.
The best match available is VB4/5/6, as VBA is a VB6 dialect, but this also not a good option as VBA is not VB6.
Sorry, but I begin to use VBA and I want/need to learn more. I will be apreaciated for any clues.
I am going to assume that since you mentioned VBA that you are looking for Excel macro help.
If this is the case, this thread should be probably moved to the VB6 forum as that is the most appropriate one that I can think of.
TnTinMN,
Yes, it sounds like what I need.
Here is a basic macro with minimal error checking. It asks you to select two ranges and it compares the first column in each range to produce a result array. It then asks you for a place to copy the results to in a worksheet.
Private Sub CompareColumns()
Dim Col1 As Range
Dim Col2 As Range
On Error Resume Next
Set Col1 = Application.InputBox("Select 1st column", , ActiveCell.Address, _
, , , , vbString)
If Col1 Is Nothing Then Exit Sub
Set Col2 = Application.InputBox("Select 2nd column", , ActiveCell.Address, _
, , , , vbString)
If Col2 Is Nothing Then Exit Sub
On Error GoTo 0 ' cancel resume next
'Determine the longer list
Dim shortCol As Range
Dim LongCol As Range
If Col1.Rows.Count < Col2.Rows.Count Then
Set shortCol = Col1
Set LongCol = Col2
Else
Set shortCol = Col2
Set LongCol = Col1
End If
Dim LongColMatched() As Boolean ' Used to indicate matched value used if duplicates exist
ReDim LongColMatched(0 To LongCol.Rows.Count - 1)
' declare a result array …
I am going try to rephrase your question and ask that you confirm whether or not it matches your ultimate goal.
You have two lists of of numbers. One of the lists is longer than other and it contains all the values in the shorter list.
You need to create a side by side comparison of the two lists showing a blank cells in the column representing the shorter list where a number exists in the longer list but not in the shorter list.
Does this sound like what you are after?
There is not much info here to offer advice on, but the basic pattern could be something like this:
Dim strm As IO.Stream = IO.File.OpenRead("pdfText.txt")
Dim sr As New IO.StreamReader(strm)
Dim line As String
Dim trimchars() As Char = {" "c}
Do While sr.Peek <> -1
line = sr.ReadLine()
If line.TrimStart(trimchars).StartsWith("SITUATIONAL") Then
' found pattern
End If
Loop
sr.Close()
Conversion from type 'DataRowView' to type 'String' is not valid.
try something like this:
TextBox1.Text = CType(ComboBox1.Items(ComboBox1.SelectedIndex), DataRowView).Row("FieldName").ToString()
or
TextBox1.Text = CType(ComboBox1.Items(ComboBox1.SelectedIndex), DataRowView).Row(#).ToString()
where # is the zero based column index of field you want.
perhaps this article can help you.
http://visualbasic.about.com/od/quicktips/qt/vb6pack_deploy_wiz2.htm
Report.Database.Tables(1).SetDataSource rs, 3'>>> Where the error shows up
If "1" (the only subscript there) is out of range, are sure that that should not be:
`Report.Database.Tables(0).SetDataSource rs, 3
Also make sure that your application is compiled as a 32-bit application (x86).
GrimJack,
Thank you for posting that link!!!
If the datagridview is backed by a datatable filled from something (a database query), then something like this would work.
// make a datatable to simulate a table filled from a database
DataTable dt = new DataTable();
DataRow r ;
dt.Columns.Add("item", typeof(string));
dt.Columns.Add("quantity", typeof(decimal));
dt.Columns.Add("weight", typeof(decimal));
r = dt.NewRow(); r[0] = "apples"; r[1] = 10; r[2] = 0.5; dt.Rows.Add(r);
r = dt.NewRow(); r[0] = "oranges"; r[1] = 20; r[2] = 0.6; dt.Rows.Add(r);
r = dt.NewRow(); r[0] = "bananas"; r[1] = 100; r[2] = 0.25; dt.Rows.Add(r);
dt.AcceptChanges();
// assume that dt was filled from a database with the 3 columns defined above
// you could add a total weight for item column
DataColumn twi = dt.Columns.Add("Tot_Weight", typeof(decimal));
// add an expression to the column to automatically do the multiplication
twi.Expression = "[quantity] * [weight]";
dataGridView1.DataSource = dt;
// if you do not want this column displayed then set it's visible property to false
dataGridView1.Columns["Tot_Weight"].Visible = true;
// add some formatting to the column
dataGridView1.Columns["Tot_Weight"].DefaultCellStyle.Format = "N3"; // 3 places after decimal mark
dataGridView1.Columns["Tot_Weight"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
// now to get a total of the total weight column
decimal totweight = (from r2 in dt.AsEnumerable()
select (decimal) r2["Tot_Weight"]
).Sum();
textBox1.Text = totweight.ToString();
// or without adding the total weight column
// and just do the calculation
decimal totweight2 = (from r2 in dt.AsEnumerable()
select (decimal) r2["quantity"] * (decimal) r2["weight"]
).Sum();
The routine that I posted does not clone Children nor Content. It may be possible to write a generic cloner, but write know I do not see an easy way to do so.
It is be fairly easy to write a simple cloner for the pattern of ContentControl <- Grid <- Shape.
private void Button1_Click(object sender, RoutedEventArgs e)
{
ContentControl cc = ContentControlCloner(ContentControl1);
cc.Margin = new Thickness(100, 0, 0, 0);
Canvas1.Children.Add(cc);
}
private Shape ShapeCloneProperties(Shape source)
{
Shape clone = null;
switch (source.GetType().Name)
{
case "Ellipse":
clone = new Ellipse();
break;
case "Line":
clone = new Line();
break;
case "Path":
clone = new Path();
break;
case "Polygon":
clone = new Polygon();
break;
case "Polyline":
clone = new Polyline();
break;
case "Rectangle":
clone = new Rectangle();
break;
default:
throw new ArgumentException("Invalid shape");
}
foreach (System.Reflection.PropertyInfo pi in source.GetType().GetProperties())
{
if (pi.CanWrite && pi.CanRead)
{
pi.SetValue(clone, pi.GetValue(source, null), null);
}
}
return clone;
}
private ContentControl ContentControlCloner(ContentControl source)
{
ContentControl clone = new ContentControl();
clone.Name = "fred";
foreach (System.Reflection.PropertyInfo pi in typeof(ContentControl).GetProperties())
{
if (pi.Name == "Content")
{
Grid gr = (Grid)source.Content;
Grid gridclone = GridCloneProperties(gr);
gridclone.Children.Clear();
Shape sh = ShapeCloneProperties((Shape)gr.Children[0]);
gridclone.Children.Add(sh);
clone.Content = gridclone;
}
else
{
if (pi.CanWrite && pi.CanRead)
{
pi.SetValue(clone, pi.GetValue(source, null), null);
}
}
}
return clone;
}
private Grid GridCloneProperties(Grid source)
{
Grid clone = new Grid();
foreach (System.Reflection.PropertyInfo pi in typeof(Grid).GetProperties())
{
if (pi.CanWrite && pi.CanRead)
{
pi.SetValue(clone, pi.GetValue(source, null), null);
}
}
return clone;
}
}
Modify your code like this:
'Read each line after first seven lines
For I = 1 To 7
If inputFile.Peek >= 0 Then
strWeather = inputFile.ReadLine()
Stop
End If
Next
While inputFile.Peek >= 0
strWeather = inputFile.ReadLine()
Stop
key = CInt(strWeather.Substring(1, 3))
'store the entire line in the collection
colWeather.Add(strWeather, CStr(key))
End While
Then run it and inspect strWeather each time then code stops. Most likely you have an empty line if the text file that is being read.
Hit F5 to continue execution.
I still get my catch message box. At this point I'm not really sure what is happening anymore...
Comment out the Try-Catch statements and let the debugger show you where the error is occuring. Inspect the variables and see if they are what you would expect.
For some guidance on debugging, read : Debugging in Visual Basic .NET. It is old but still valid.
That was fast.
I was in the neighborhood and it was an easy question. :)
Please mark the thread as answered, if you don't have any more questions on the topic.
Thanks.
If I'm not mistaken, these user-scope settings will not be there when the application is restarted.
You are misktaken.
User-Scoped settings would be pretty useless if they could not be saved. The default is for them to be saved on application shutdown, but you can also issue the statement My.Settings.Save()
to force a save of their current state.
for example in VB.net ....
but in C# this doesn't seem to work, i can hide the form fine (this.hide();) but when in the second form i cannot recall the form (form1.show();) as it doesn't seem to exsist, but i tested it by taking out the .hide(); and it just sits in the background (unpleasant) lol
That is because VB.Net with the Application Framework enabled automagically creates and maintains a globally accessible instance of all forms in your project. This is one feature that I wish that they never implemented; it does make some things easier (I guess that was the intent), but it really messes with the minds of programmers who are not used to having objects automagically created and made accessible.
I really dislike the idea globally accessible objects and feel that a class needs a reference to an external object, that reference should be purposely set. The reference can either be a property or passed in the constructor.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(this);
this.Hide();
f2.ShowDialog();
}
}
}
Now for Form2:
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
private Form _FormThatShowedMe;
public Form2(Form FormThatShowedMe) // pass reference
{
if (FormThatShowedMe == null)
{
throw new ArgumentException("Hey! I need a valid form");
}
InitializeComponent();
_FormThatShowedMe = FormThatShowedMe;
}
private void button1_Click(object sender, EventArgs e)
{
_FormThatShowedMe.Show();
this.Close();
} …
If you just try to open the vb6 project in vb10 it should automatically start the conversion wizard. It will take you through the conversion and ask you if you want to see the resulting log file when done. In my experience it does a decent job of converting.
^^ Misinformation
Here is VS Express 2008 link that still works:
Visual Studio 2008 Express Edition ISO
Upgrading much other than simple programs may be more hassle than it is worth.
Here is an article that discusses the issues: On Migrating a VB Project to VB.NET
Also note that the VB6Compatibilty library that is used in upgrading was declared obsolete in .Net 4.0.
Your file is open with the filestream object when you try to open it via Proc.Start();
.
At a minimum, add FS.Flush();
after writing out the bytes to flush the buffer to disk. Preferably, close the file before calling Proc.Start();
.
Here are some articles you may want to investigate:
I take it that you are using VS2008 or ealier when we still had deployment projects.
The only way that I know that the "Add Project Output Group" dialog would be empty is if the startup project is the only one in the soultion that holds the setup project.
What you are expecting is something like this where there is another project from which to populate the dialog.
Please confirm that this is the situation or not.
Posting a picture similar to the ones I posted would be helpful.
Perhaps something like this, where "ellispse1" in the name of the ellipse you defined in XAML.
private void button1_Click(object sender, RoutedEventArgs e)
{
Ellipse copyel = EllipseCloneProperties(ellipse1);
// set your positioning properties
canvas1.Children.Add(copyel);
}
private Ellipse EllipseCloneProperties(Ellipse source)
{
Ellipse clone = new Ellipse();
foreach (System.Reflection.PropertyInfo pi in typeof(Ellipse).GetProperties())
{
if (pi.CanWrite && pi.CanRead)
{
pi.SetValue(clone, pi.GetValue(source, null), null);
}
}
return clone;
}
Sorry but that, I forgot a line of code to add the newrow to the table.
For Each r As DataRow In dataTable.Rows
newrow = datatableAllString.NewRow
For i As Int32 = 0 To datatableAllString.Columns.Count - 1
newrow(i) = r.ItemArray(i).ToString()
Next i
datatableAllString.Rows.Add(newrow)
Next r
This is not an ideal solution, but I think that it has the least chance of confusing you.
We will create a new datatable with only string values.
Dim fileName As New IO.FileInfo(frmStepOne.ofdFileSearch.FileName)
Dim connection As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBase IV;Data Source='" & fileName.DirectoryName & "'")
Dim tablename As String = fileName.Name.Substring(0, fileName.Name.Length - fileName.Extension.Length)
Dim command As New OleDb.OleDbCommand(tablename, connection)
command.CommandType = CommandType.TableDirect
Dim dataTable As New DataTable
connection.Open()
Dim reader As OleDb.OleDbDataReader = command.ExecuteReader
dataTable.Load(reader)
connection.Close()
connection.Dispose()
'----------------
Dim datatableAllString As New DataTable
For Each col As DataColumn In dataTable.Columns
datatableAllString.Columns.Add(col.ColumnName, GetType(String))
Next
Dim newrow As DataRow
For Each r As DataRow In dataTable.Rows
newrow = datatableAllString.NewRow
For i As Int32 = 0 To datatableAllString.Columns.Count - 1
newrow(i) = r.ItemArray(i).ToString()
Next i
Next r
dataTable.Dispose()
'----------------
DataGridView1.DataSource = datatableAllString
My issue: I have a datagridview and a DB file with ~100 columns and ~200 rows of data. This data is imported to the DGV onLoad().
Does this mean that you first fill a datatable from the database and then set the dgv.DataSource equal to the datatable?
If so, that is the source of the problem as the dgv as bound to the datatable. The datatable is where the column type is defined as double.
You could add an unbound column to the dgv and set the value for each row as you need to. You would then hide the original column.
Edit:
Please show the Form_Load method
Here are two options:
This one whould update after you leave the first column.
private void dgv1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
return;
if (sender is DataGridView && e.ColumnIndex == 0)
{
DataGridView dgv = (DataGridView)sender;
if (dgv1.Equals(dgv))
{
// set the value as needed
dgv.Rows[e.RowIndex].Cells[2].Value = "fred";
}
}
}
This one updates immediately.
private DataGridViewComboBoxEditingControl cboxEdit;
private void EditComboBox_SelectionChangeCommitted(object sender, System.EventArgs e)
{
// set the value as needed
dgv1.CurrentRow.Cells[2].Value = "wilma";
}
private void dgv1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dgv1.CurrentCell.ColumnIndex == 0 && e.Control is DataGridViewComboBoxEditingControl)
{
if (cboxEdit != null)
{
cboxEdit.SelectionChangeCommitted -= EditComboBox_SelectionChangeCommitted;
}
cboxEdit = (DataGridViewComboBoxEditingControl)e.Control;
cboxEdit.SelectionChangeCommitted += EditComboBox_SelectionChangeCommitted;
}
}
I'm not sure if this is applicable to your situation, but take a look at : http://cgeers.com/2008/02/03/monitoring-a-smartcard-reader/
I suggest that you take the time to go through this information: Working with Datasets in Visual Studio
In particular, the walkthroughs at the bottom of the Dataset Designer topic.
Can anyone tell me if this is possible?
Yes it can be done, but you may not like dealing with some of the after effects of doing it.
First you need to get the correct window handle using the API function FindWindow with the proper class name. For Word this is "OpusApp" and I believe it is "XLMAIN" for Excel.
Running a search on "HttpContext.Current null" I cam across this article that may explain what you are seeing.
when i try to delete a certain row it gives me the previous exception
What previous exception?
Is Bridge_Number a Text field? If not, get rid of the single qotes around it in the query. What column index does Bridge_Number represent in the listview? Your query indicates that it is the first column.
Here is an example that you can follow to read in the DBASE file. It is slightly different than the method you are using.
Dim ofd As New OpenFileDialog
With ofd
.Filter = "DBASE File (*.dbf)|*.dbf"
.Multiselect = False
.CheckFileExists = True
End With
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fi As New IO.FileInfo(ofd.FileName)
Dim cn As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=dBase IV;Data Source='" _
& fi.DirectoryName & "'")
Dim TableName As String = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length)
Dim cmd As New OleDb.OleDbCommand(TableName, cn)
cmd.CommandType = CommandType.TableDirect
Dim dt As New DataTable
cn.Open()
Dim rdr As OleDb.OleDbDataReader = cmd.ExecuteReader
dt.Load(rdr)
DataGridView1.DataSource = dt
cn.Close()
cn.Dispose()
End If
i know basics of java morderately well. will catching C# be easy given this ?
That is something that only you can decide after giving it a go. We all have different aptitudes. All I can say is that some refer to C# as Microsoft's answer to java, so it may seem familiar to you. However, I found that similiarities between two languages can lead to unrealistic expectations and frustration when the subject language does things differently.
Also, don't think that you are going to learn it all in a short period of time or at all. The .Net framework is huge and growing. Whatever .Net language you use is just a means to use the framework.
Personally, I try to not use language specific contructs as much as possible, but rather use the framework types and classes as much as possible. This makes it easier for me to move between VB and C#. Some would say that this is a poor style. Fashions change and if I am not being payed to produce code to someone's standard, who are they to tell me that I am doing to wrong. :)
seeing the code examples above , i guess i can write C# code in place of VB code , and still all will be well ? i think i remember seeing project options on the opening page of VS 2010... so if i want to code in C# or C++ or VB , ill just have …
edit: oracle 9i is obsolete , and that is what we were told to use at college(along with vb6),
OP, thanks for that bit of info. I've often wondered why I see so many from your part of the world trying to learn VB6.
and im not going to listen to them.
I hope the college's software selection is just a recommendation and not a requirement.
need some help in choosing what would be a good backend software as well. i only have some theoritical knowledge about sql in general, havent done anything practical. would mysql be a good option?
MySql is probably a valid choice, but I would recommend Microsoft SQL Server Express (free also) or MS Sql Server CE. At least with the MS products, you should have less chance of bumping into issues whilst you are trying to learn the programming language and there are lots of examples available for them as well.
For programming language learning resources:
In addition to rubberman's comment:
you are summing in "coursesCount:, but comparing "courses".
Is this the logic you intended?
You will likely get several techniques for doing this. Here are two that I find preferable.
Public Class Form1
Sub LaunchForm2()
Dim f2 As New Form2
f2.needVariable = 2 ' pass as property
f2.ShowDialog()
End Sub
Sub LaunchForm3()
Dim f3 As New Form3(3) ' pass in constructor
f3.ShowDialog()
End Sub
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
LaunchForm2()
LaunchForm3()
End Sub
End Class
'Declare a property on the 2nd form
Public Class Form2
Inherits Form
Private _needVariable As Int32
Public Property needVariable() As Int32
Get
Return _needVariable
End Get
Set(ByVal value As Int32)
_needVariable = value
End Set
End Property 'needVariable
Private Sub Form2_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
MsgBox("F2: " & needVariable.ToString())
Me.Close()
End Sub
End Class
' pass the value in the form's constructor
Public Class Form3
Inherits Form
Private needVariable As Int32
Public Sub New(ByVal needVariable As Int32)
Me.needVariable = needVariable
End Sub
Private Sub Form2_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
MsgBox("F3: " & needVariable.ToString())
Me.Close()
End Sub
End Class
@TnTinMN: Way back, I did lots of VBA programming on Excel. I always found VB.NET some super VBA. When I first met C#, well, I was lost. Consise syntax, lambda expressions, predicate delegates, etc. etc. I'm sure you can do all those things in VB.NET, but it seems as if it always has to happen via some sort of workaround. But correct me if I'm wrong.
VB.Net is not a some form a super VBA. It is an entirely different language. Granted, it still maintains much of the same syntax structure of VB6 just like VB6 maintained a lot syntax structure of BASIC. However, Vb.Net is just that, it is a .Net language that after compiles to the same Common Intermediate Language that the C# compiler compiles to. Hence the ease of using a C# library in VB.Net or visa versa.
I am not sure extactly what you mean here by "workaround" and I don't want to invoke a preferred language war, but I see a lot of this as an issue of style, familiarity and personal preference.
C#'s syntax is concise because someone defined a shorthand notation versus a more verbose statement.
Let us take a simple example:
C#
delegate int del(int i);
static void Main(string[] args)
{
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25
}
VB
Delegate Function del(i As Integer) As Integer
Private Shared Sub Main(args As String())
Dim myDelegate As del = Function(x) x * …
Personally I prefer VB.Net.
If your goal is improve marketable skills in a few weeks and you already have a C background, it will be much easier for you to pick-up C#. Unfortonately, VB is viewed by many as an inferior language (even though it essentially equal to C#).
MS claims to be working on bringing parity to the two languages, but in my view this has primarily focused on adding functionality to C# that previously only existed in VB and not the other way around. C# is still their flagship .Net language and is/was used to write a the framework libraries.
Officially, VB6 is dead, but it is tenacious. MS updated the VBA language (VBA is essentially an interpreted form of VB6) in 2010, so there is some hope that they will recant their decision and release a VB7 at some point. Any effort to learn VB6 should be viewed as an effort to build up your skills repertoire. (I.E. it can not hurt to know it.) Old code will still need to be maintained and the VB6 runtime is supposed to be supported through the Windows 8 lifecycle.
Scrap emmbedding the video files.
Bring up the Solution Explorer: View Menu - > Solution Explorer
Add New Folder: Project Menu -> New Folder (Let's Name it Video)
In the "Solution Explorer" window, Selected the "Video" folder and then right-click->Add->Existing Item
Now Select your video files to include in the project.
For each video you add, set it's properties like this:
Build the Application.
Set the Publishing Options:
Now Publish it.
You can then load the video like this:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
AxWindowsMediaPlayer1.currentMedia = AxWindowsMediaPlayer1.newMedia(ExecutionPath() & "\Video\Video1.avi")
End Sub
Public Function ExecutionPath() As String
Return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
End Function
try:Dim swriter As New StreamWriter(Application.StartupPath & "\TeachersCourses.dat", append:=True)
How are you doing the Deployment?
That's a new error message to me :/
Usually it's along the lines of cannot delete file blah blah...
Are you sure you do not have an instance of the program running? It may have crashed and did not fully unload from memory and release the file. Sometimes you will need to reboot to clear things up.
Assuming that the field is stored as a DateTime type,
If dr.IsDBNull(5) Then
TxtAppointmentdate.Text = ""
Else
TxtAppointmentdate.Text = dr.GetDateTime(5).ToShortDateString()
End If
Tinnin,
Why are you going through all this work just to read in values from an Excel file? What does converting it to a CSV format gain you?
You could use the Excel interop to read the values directly.
Alternatively, you could use ADO.Net to read the files without any dependence on having Excel installed.
I knew that I posted on this before and finally found it:
Do you mean play an embedded file? If, so I believe you will first have to write the file out to the disk first and then point the media player to that file.