Tuesday, June 23, 2009

How to change mouse Icon when drag the items from DataGridView to another using VB.NET

How to change mouse Icon when drag the items from data grid view using VB.NET

Let say you have some data rows in data grid and you can select multiple rows from grid and you can drag selected rows into some other data grid or other controls

This time you will get default mouse icon and if you want to change the mouse icon with custom image then write following code in your data grid view events

Set DataGridView Properties at design time Allowdrop = true

Following code are tested with

1) .NET Framework 2.0

2) Visual Studio 2005

3) VB.NET Window Application

4) Window XP


'Following event will help to drag items on mouse left click button and this event will activate drag drop event of data grid view


Private Sub DataGridView1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown


Dim gridColumnIndex As Integer

'Get the Index of Row which is being Dragged

'We would use this Index on Drop to identify which Row was dragged and get the values from that row


If e.Button = Windows.Forms.MouseButtons.Left Then

gridColumnIndex = DataGridView1.HitTest(e.X, e.Y).RowIndex

If gridColumnIndex > -1 Then

DataGridView1.DoDragDrop(gridColumnIndex, DragDropEffects.Move)

End If

End If

End Sub


'This event will remove default mouse icon

Private Sub DataGridView1_GiveFeedback(ByVal sender As Object, ByVal e As System.Windows.Forms.GiveFeedbackEventArgs) Handles DataGridView1.GiveFeedback

e.UseDefaultCursors = False

End Sub


'This event will change mouse icon with custom icon based on the one item selected or multiple items selections

Private Sub DataGridView1_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles DataGridView1.DragOver

e.Effect = DragDropEffects.Move

'if selected item is 1 then set desired icon, if more

the one then set multidrag icon else set default

If DataGridView1.SelectedRows.Count = 1 Then

Windows.Forms.Cursor.Current = New Cursor("C:\Icon\ImageSingleDrag.ico")

ElseIf DataGridView1.SelectedRows.Count > 1 Then

Windows.Forms.Cursor.Current = New Cursor("C:\Icon\ImageMultiDrag.ico")

Else

Windows.Forms.Cursor.Current = Cursors.Default

End If

End Sub


'This event will change mouse icon to no Drag icon if you move item to some other place where you can't drag the items

Private Sub DataGridView1_DragLeave(ByVal sender As Object, ByVal e As System.EventArgs) Handles DataGridView1.DragLeave

Windows.Forms.Cursor.Current = New Cursor("C:\Icon\ImageNoDrag.ico")

End Sub


'This event will deselect the items from data gird

Private Sub DataGridView1_CellMouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseUp

Dim index As Integer

index = e.RowIndex

If index > -1 Then

If DataGridView1.Rows(index).Selected = False Then

Me.DataGridView1.ClearSelection()

Me.DataGridView1.Rows(index).Selected = True

End If

End If

End Sub


If are dragging yout items into DataGridView2 then write your action code in following events

Private Sub DataGridView2_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles dgNegotiationList.DragDrop

'Write your code to do action for drag items

End Sub

Problem: DataGridView CellDoubleClick and Drag drop both not woking togather

Solution: Click Here

Learn more about how to Drag and Drop items from data grid view. See the following sites.

http://www.codeproject.com/KB/cpp/DataGridView_Drag-n-Drop.aspx

http://www.pcreview.co.uk/forums/thread-3430543.php













Thursday, May 28, 2009

How to use XML in SQL Server and Oracle database Stored Procedure to create dynamic InClause for select query

How to use XML in SQL Server and Oracle database Stored Procedure to create dynamic InClause for select query


Lots of time you have a requirement to get multiple rows from database, that time you have to create InClause and send it to stored procedure.

Oracle you can pass Array to stored procedure and it will solve you purpose to create InClause inside stored procedure, (see article using link http://riteshk.blogspot.com/2009/03/how-to-send-array-as-input-parameter-to.html)

But in SQL Server database you don't have any way to pass Array to stored procedure, only way available to use XML for this.


Here I am describing the way to pass XML to create InClause in SQL server and Oracle stored procedure. XML format can be multiple types and based on that your stored procedure structure will change.


Following code has been tested in following environments


1) .NET framework 2.0

2) Oracle 10g

3) SQL Express

4) Microsoft Enterprises Library 3.0


Sample Xml which you will pass it to Stored Procedure


<ArrayList>

<Values><Value>40415</Value></Values>

<Values><Value>59556</Value> </Values>

<Values> <Value>67900</Value></Values>

</ArrayList>


Oracle Stored Procedure


CREATE OR REPLACE

PROCEDURE Pass_Array_Oracle

(

prmInClause IN XMLTYPE,

prmOutCursor OUT SYS_REFCURSOR

)

AS


BEGIN


OPEN prmOutCursor FOR

SELECT * FROM Employee EMP WHERE EMP.EMPNO IN (

SELECT

XMLTYPE.EXTRACT (VALUE (EMP),'/Value/text()').getstringval()

AS iEMPNO

FROM TABLE

(XMLSEQUENCE (prmInClause.EXTRACT ('/ArrayList/Values/Value'))) EMP );

END;


SQL Stored Procedure


CREATE PROCEDURE Pass_Array_SqlServer

(

@prmInClauseData XML

)

AS

DECLARE @XMLDocPointer INT

EXEC sp_xml_preparedocument @XMLDocPointer OUTPUT, @prmInClauseData

BEGIN

--CREATE INCLAUSE FROM INPUT PARAMETER XML VALUE

SELECT * FROM EMPLOYEE WHERE EMPNO IN (

SELECT Value FROM OPENXML (@XMLDocPointer, '/ArrayList/Values', 2)

WITH (Value NVARCHAR(36)))

END


VB.NET Code from where You will execute stored procedure


'This method will execute Oracle and SQL Server Stored Procedure and give you

'data in the form of dataset


Public Sub ExecuteStoredProcedure(ByVal xmlString As String, _

ByVal connectionString As String, ByVal spName As String, ByVal IsOracle As Boolean)

Dim employeeCommand As DbCommand

Dim dsData As New DataSet

Dim connectDB As Database = DatabaseFactory.CreateDatabase(connectionString)

employeeCommand = connectDB.GetStoredProcCommand(spName)


If IsOracle Then

connectDB.AddXmlInParameter(employeeCommand, "@prmInClauseData", xmlString)

End If

connectDB.AddCursorOutParameter(employeeCommand, "@prmOutCursor")

dsData = connectDB.ExecuteDataSet(employeeCommand)


End Sub


How to use from VB.Net code


Dim xmlString As String = "<ArrayList><Values><Value>40415</Value></Values><

Values><Value>59556</Value></Values><Values><Value>

67900</Value></Values></ArrayList>"


Dim sqlConnectionString As String = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Program Files\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\EMPLOYEE.mdf;Integrated Security=True;User Instance=True"


Dim sqlSpName As String = "Pass_Array_SqlServer"

'Execute SQL Server Stored Procedure from VB.NET Code

ExecuteStoredProcedure(xmlString, sqlConnectionString, sqlSpName, False)


'This will give you 3 nos of rows because XML have 3 Empno

MessageBox.Show(dsDataSet.Tables(0).Rows.Count)

Dim oracleConnectionString As String = "Data Source=DSNName;User ID=UserId;Password=Password;"

Dim oracleSpName As String = "Pass_Array_Oracle"


'Execute Oracle Stored Procedure from VB.NET Code

ExecuteStoredProcedure(xmlString, oracleConnectionString, oracleSpName, True)


'This will give you 3 nos of rows because XML have 3 Empno

MessageBox.Show(dsDataSet.Tables(0).Rows.Count)

Tuesday, April 21, 2009

How to add Image in the DataGridView or ListView Column, VB.NET

How to add Image in the DataGridView or ListView Column, VB.NET
 
Some time you have to display different images in the datagrid view based on column value. The simplest and fast performing way to achive this with datagridview, you add one Image column in the datatable and bind this datatable into the datagridview.
For ListView Control, you add one Image column listview item and add this item into into the listview control
 
NameSpace
Imports System.Text
Imports System.IO
 
Source Code
 
'Display Image column in the first column in the datagridview
Private Function BindDataGrid() As Integer
 
Dim rowCount As Integer
Dim dsCustomer As New DataSet
'Get related data from database
dsCustomer = GetAllCustomerData()
 
Try
 
Dim custTable As DataTable = dsCustomer.Tables(0)
Dim col As DataColumn
col = New DataColumn("Image", GetType(System.Drawing.Image))
custTable.Columns.Add(col)
col.SetOrdinal(0) 'This line will add image column in '0' place
 
'ImageList1 is ImageList control defined in the design time and add desired image (Design time) in the Imagelist Control,
For rowCount = 0 To custTable.Rows.Count - 1
If custTable.Rows(rowCount)("Dept").ToString() = "Finance" Then
   custTable.Rows(rowCount)("Image") = ImageList1.Images("ImageName1")
ElseIf custTable.Rows(rowCount)("Dept").ToString() = "Sales" Then
   custTable.Rows(rowCount)("Image") = ImageList1.Images("ImageName2")
Else
   custTable.Rows(rowCount)("Image") = ImageList1.Images("ImageName3")
End If
Next
 
   DataGridView1.DataSource = custTable
   DataGridView1.Columns(0).Width = "20"
 
   Return custTable.Rows.Count
 
Catch ex As Exception
    Throw ex
End Try
 
End Function
 
Note:  Another way to add Image in the ImageList Object at runtime
         ImageList.Images.Add(Bitmap.FromFile("../Icons/Image1.ico"))
 
'Display Image column in the first column in the listview control
Private Function BindListView() As Integer
 
Dim rowCount As Integer
Dim dsCustomer As New DataSet
'Get related data from database
dsCustomer = GetAllCustomerData()
 
Try
 
'Clear all the previous data if any, to overcome from binding duplicate data
ListView1.Clear()
' Set the view to show details. This is for to display all the rows and columns
ListView1.View = View.Details
 
'Design time add desired image in the Imagelist Control, ImageList1 is ImageList control defined in the design time
ListView1.SmallImageList = ImageList1
 
'Add columns,
ListView1.Columns.Add("Cust_Name", -2, HorizontalAlignment.Left)
ListView1.Columns.Add("Cust_Address", -2, HorizontalAlignment.Right)
 
Dim item As New ListViewItem
Dim custTable As DataTable = dsCustomer.Tables(0)
 
For rowCount = 0 To custTable.Rows.Count - 1
If custTable.Rows(rowCount)("Dept").ToString() = "Finance" Then
    item = New ListViewItem(custTable.Rows(rowCount)(0).ToString(), 0) 'Image1
ElseIf custTable.Rows(rowCount)("Dept").ToString() = "Sales" Then
    item = New ListViewItem(custTable.Rows(rowCount)(0).ToString(), 1) 'Image2
Else 'Other Dept
     item = New ListViewItem(custTable.Rows(rowCount)(0).ToString(), 2) 'Image3
End If
 
     item.SubItems.Add(custTable.Rows(rowCount)(0).ToString())
     item.SubItems.Add(custTable.Rows(rowCount)(1).ToString())
      ListView1.Items.Add(item)
Next
 
Return custTable.Rows.Count
 
Catch ex As Exception
     Throw ex ' Handle Exception here
End Try
 
End Function
 
Note:   'Another way to add Image in the custTable Row at runtime
           custTable.Rows(rowCount)("Image") = New System.Drawing.Bitmap ("../Icons/Image1.ico")

Friday, April 17, 2009

ListView Control De-select it selected value when click on other controls in .NET

ListView Control De-select it selected value when click on other controls in .NET

Following example tested with VB.NET Window Form, .NET Framework 2.0 and IE 6.0

Problem:

  1. Load listview control
  2. Select some rows from listview
  3. Now select some other controls in the form
  4. All listview selected rows are de-selected

Solution:

Select your listview control on lost focus of listview event


Private Sub ListView1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.LostFocus

ListView1.Select()

End Sub


Note:
Here the simple way to select/Unselect listview control programatically

'Select Items from ListView Control
ListView1.Items(0).Selected = True

ListView1.Select()

'Un-Select Items from ListView Control
ListView1.Items(0).Selected = False
ListView1.Select()

Thursday, April 09, 2009

Confirm Popup message box with “Yes/No” button instead of “Ok/Cancel”

Confirm Popup message box with "Yes/No" button instead of "Ok/Cancel" In the javascript you have 'Confirm' function to popup message box and this message box comes with "Ok" and "Cancel" button but sometime you might have a requirement to display "Yes" and "No" button popup message box instead of "ok" and "Cancel". To achive this we have lots of work around. One of that is go and overrite window confirm function with vbscript. So you are still using JavaScript and Confirm function to display popup message box with "Yes" and "No" button and this fucntion will return "True" or "False" based on which button clicked. Copy and past following code in your aspx page before <Body> tag. This will give you popup message box on page load


<script language=javascript>

/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>=5)
function window.confirm(str)
{
execScript('n = msgbox("'+str+'","4132")', "vbscript");
return(n == 6);
}
@end @*/
var r = confirm("Do you think you can do it?");
alert(r);


</script>


If you want this popup message box on click of button then call this fucntion on button click like below.


<asp:Button runat="server" Text="Button" OnClientClick="confirm('Do you think you can do it?')" ></asp:Button>


Message box WITH JavaScript Message box WITHOUT JavaScript

Friday, March 27, 2009

Error: ORA-30683: failure establishing connection to debugger

Error: ORA-30683: failure establishing connection to debugger or

ORA-06512: at "SYS.DBMS_DEBUG_JDWP"

In Oracle SQL Developer Tool


If you are getting following error while debug your stored procedure then you can try following steps


  1. In the Oracle SQL Developer Tool
  2. Go to "Tool" Menu
  3. Go to "Preferences"
  4. Go to "Debugger"
  5. Check "Prompt for Debugger Host for Database Debugging" check box
  6. Click "OK"
  7. Now whenever you will be debug it will prompt
  8. "Debugger Host for Database Debugging" dialog box
  9. Type you local system IP Address
  10. Click "OK"

Thursday, March 12, 2009

Execute Oracle Stored Procedure/Query FROM SQL Server

Execute Oracle Stored Procedure/Query FROM SQL Server


Most of the time your project requirement to work with two databases, In
some scenarios you want to execute one database stored procedure from
another database. Here I am giving the example to execute Oracle stored
procedure from SQL server database.
To achieve this first you have to set up link from SQL server to Oracle


How to link Oracle Database from SQL server


http://blogs.techrepublic.com.com/datacenter/?p=133

http://support.microsoft.com/kb/280106

http://msdn.microsoft.com/en-us/library/aa259589(SQL.80).aspx


To execute an Oracle Stored Procedure from SQL Server you can try
the following: You can make a sample package named Project_Package
with the procedure named TestProcedure:


Package Header:


PROCEDURE TestProcedure
(
I_Parameter1 IN NUMBER,
I_Parameter2 IN NUMBER,
O_Parameter1 OUT NUMBER,
O_Parameter2 OUT NUMBER
);


Package Body:


PROCEDURE TestProcedure
(
I_Parameter1 IN NUMBER,
I_Parameter2 IN NUMBER,
O_Parameter1 OUT NUMBER,
O_Parameter2 OUT NUMBER
) AS
BEGIN
O_Parameter1 := I_Parameter1 + 1;
O_Parameter2 := I_Parameter2 + 1;
END TestProcedure;


Then we create a SQL Server Stored Procedure to Wrapp the Oracle

Store Procedure Invocation, the T-SQL inside the procedure for this

sample is the following:


DECLARE
@l_i_parameter1 INTEGER
DECLARE
@l_i_parameter2 INTEGER
DECLARE @l_o_parameter1 INTEGER
DECLARE
@l_o_parameter2 INTEGER

SET
@l_i_parameter1 = 5
SET @l_i_parameter2 = 10
SET @l_o_parameter1 = 0
SET @l_o_parameter2 = 0

EXECUTE
( 'begin Project_Package.TestProcedure(?,?,?,?); end;',
@l_i_parameter1, @l_i_parameter2, @l_o_parameter1
OUTPUT, @l_o_parameter2 OUTPUT) AT DBLINK_NAME;

SELECT
@l_o_parameter1, @l_o_parameter2

I Hope this sample illustrate the concept. Also I want to mention that
this sample only works with simple output parameters, if you are trying
to query for result sets I recommend trying the OPENQUERY statement
instead.

OR

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

Using OPENQUERY
If exists (select * from master..sysservers where
srvname = '
OracleDemo')
     exec sp_dropserver 'OracleDemo'
go
exec sp_addlinkedserver @server = N'OracleDemo',
    @srvproduct = N'',
    @provider = N'SQLOLEDB', 
    @datasrc = @@servername
go
select * into #Ta from OPENQUERY(OracleDemo,
'exec yourSproc')
select * from #Ta
drop table #Ta
go 
USING SP_EXECUTEESQL
DECLARE @rc INT
DECLARE @v_sql NVARCHAR(4000)
DECLARE @vc_servername VARCHAR(100)

DECLARE c_myservers CURSOR
FOR SELECT
servername
FROM listservers
WHERE active=1
FOR READ ONLY
OPEN c_myservers
FETCH NEXT FROM c_myservers INTO @vc_servername
WHILE (@@FETCHSTATUS = 0 )

BEGIN

SET @v_sql = N'SELECT name, id FROM ['+@vc_servername +
'].dbname.joe.titles'

EXEC @rc = sp_executesql @v_sql
-- if @rc <> 0
--- etc...

FETCH NEXT FROM c_myservers INTO @vc_servername

END
CLOSE c_myservers
DEALLOCATE c_myservers

COMPARISION

Rather your choice is between:

SELECT @sql = 'SELECT .... FROM ' + @server + 'catalog.schema.tbl'

and

SELECT @sql = 'SELECT ... FROM OPENQUERY(' + @server + ', ' +
'''SELECT ... FROM catalog.schema.tbl'')'

That is, accessing the table in four-part notation, or running a
pass-through query.