Quantcast
Channel: Windows Forms Data Controls and Databinding forum
Viewing all 2535 articles
Browse latest View live

Multiselect in checkBoxList

$
0
0

Hello

I'm trying to bind the table to checkBoxList as a value and a member (for example: binding a table with columns JobID and JobNumber ) and return both the values in checkbox. Is there any way for multiselect in checkBoxList.   


how I can populate rate from while selecting the item code from gridview column

$
0
0

Hi

I have a gridview control gv_1 with following column

Itemcode, Rate, Total. Item code is combo box dropdown.

DataGridViewComboBoxColumn cb = (DataGridViewComboBoxColumn)this.dataGridViewInvoice.Columns[0];

How I can bring Item Rate automatically  while selecting the code in the dropdown of the gridview.  Which event can be used to get rate. 

Please help

Pol


polachan

C# TextFieldParser Only Reading Last Record

$
0
0

I'm using the following to browse through folders to find the CSV file I need (big function, somewhat sloppy right now).

It pulls the last record and sticks it in the DGV with no problems, but the file I clicked has 4 records.  I tried just setting the datasource but these files don't have headers, hence the adding rows one at a time (just in case someone wonders).  Anybody know why it's not catching any of the other rows in the file?  I'm tinkering with using csvReader.ReadLine() instead of ReadFields() but for unknown reasons I get the red squiggles when I swapped that.

private void button1_Click(object sender, EventArgs e)
        {
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "csv files (*.csv)|*.csv"; //|All files (*.*)|*.*
            openFileDialog1.FilterIndex = 2;
            openFileDialog1.RestoreDirectory = true;

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                dataGridView1.Columns.Clear();
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {

                            DataTable csvData = new DataTable();

                            try
                            {
                                string s = openFileDialog1.FileName;
                                using (TextFieldParser csvReader = new TextFieldParser(s))
                                {
                                    csvReader.SetDelimiters(new string[] { "," });
                                    csvReader.HasFieldsEnclosedInQuotes = true;
                                    //read column names
                                    string[] colFields = csvReader.ReadFields();
                                    foreach (string column in colFields)
                                    {
                                        DataColumn datecolumn = new DataColumn(column);
                                        datecolumn.AllowDBNull = true;
                                        csvData.Columns.Add(datecolumn);

                                    }
                                    while (!csvReader.EndOfData)
                                    {
                                        string[] fieldData = csvReader.ReadFields();
                                        //Making empty value as null
                                        for (int i = 0; i < fieldData.Length; i++)
                                        {
                                            if (fieldData[i] == "")
                                            {
                                                fieldData[i] = null;
                                            }
                                        }
                                        csvData.Rows.Add(fieldData);
                                        dataGridView1.ColumnCount = csvData.Columns.Count;
                                        dataGridView1.Rows.Add(fieldData);
                                    }
                                }

                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }

        }


May the fleas of a thousand camels feast happily on the lower regions of your enemies. And may their arms be too short to scratch!



Database DELETE Command error

$
0
0
I think there is some coding error in my project so that I failed in many databases. . Here I need one help in delete command... save and add command works well

code is below

Imports System.Data.SqlClient

Public Class Form1
    Private MyDatAdp As New SqlDataAdapter
    Private MyCmdBld As New SqlCommandBuilder
    Private MyDataTbl As New DataTable
    Private MyCn As New SqlConnection
    Private MyRowPosition As Integer = 0

    Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        MyCn.Close()
        MyCn.Dispose()
    End Sub
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        MyCn.ConnectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=F:\My Files\Project\Add-Update-Delete\Add-Update-Delete\Database1.mdf;Integrated Security=True"
        MyCn.Open()
        MyDatAdp = New SqlDataAdapter(“Select* from Contact”, MyCn)
        MyCmdBld = New SqlCommandBuilder(MyDatAdp)
        MyDatAdp.Fill(MyDataTbl)
        Dim MyDataRow As DataRow = MyDataTbl.Rows(0)
        Dim strName As String
        Dim strState As String
        strName = MyDataRow(“ContactName”)
        strState = MyDataRow(“State”)
        TxtName.Text = strName.ToString
        TxtState.Text = strState.ToString
        Me.showRecords()
    End Sub
    Private Sub showRecords()
        If MyDataTbl.Rows.Count = 0 Then
            txtName.Text = “”
            txtState.Text = “”
            Exit Sub
        End If
        txtName.Text = MyDataTbl.Rows(MyRowPosition)(“ContactName”).ToString
        txtState.Text = MyDataTbl.Rows(MyRowPosition)(“State”).ToString
    End Sub

    Private Sub BtnFirst_Click(sender As Object, e As EventArgs) Handles BtnFirst.Click
        MyRowPosition = 0
        Me.showRecords()
    End Sub

    Private Sub BtnPrevious_Click(sender As Object, e As EventArgs) Handles BtnPrevious.Click
        If MyRowPosition > 0 Then
            MyRowPosition = MyRowPosition - 1
            Me.showRecords()
        End If
    End Sub

    Private Sub BtnNext_Click(sender As Object, e As EventArgs) Handles BtnNext.Click
        If MyRowPosition < (MyDataTbl.Rows.Count - 1) Then
            MyRowPosition = MyRowPosition + 1
            Me.showRecords()
        End If
    End Sub

    Private Sub BtnLast_Click(sender As Object, e As EventArgs) Handles BtnLast.Click
        If MyDataTbl.Rows.Count > 0 Then
            MyRowPosition = MyDataTbl.Rows.Count - 1
            Me.showRecords()
        End If
    End Sub

    Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
        Dim MyNewRow As DataRow = MyDataTbl.NewRow()
        MyDataTbl.Rows.Add(MyNewRow)
        MyRowPosition = MyDataTbl.Rows.Count - 1
        Me.showRecords()
    End Sub

    Private Sub BtnDelete_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnDelete.Click
        Dim MyDatAdp = New SqlDataAdapter(“Select* from Contact”, MyCn)

        If MyDataTbl.Rows.Count <> 0 Then
            MyDataTbl.Rows(MyRowPosition).Delete()
            MyRowPosition = 0
            MyDatAdp.Update(MyDataTbl)

        End If
    End Sub

    Private Sub BtnSave_Click(ByVal sender As Object, ByVal e As EventArgs) Handles BtnSave.Click
        If MyDataTbl.Rows.Count <> 0 Then
            MyDataTbl.Rows(MyRowPosition)(“ContactName”) = txtName.Text
            MyDataTbl.Rows(MyRowPosition)(“state”) = txtState.Text
            MyDatAdp.Update(MyDataTbl)
        End If
    End Sub
End Class

This is the Error while deleting data

DataGridView displays column names out of order; How do I keep my "ID" column displaying as the first column?

$
0
0

The code shown below displays column names in a DataGridView. Clicking button1 and button2 changes the "ID" column from being included in the display to being excluded from the display. The number of columns displayed is also changed. 

With "//DataTable table = new DataTable();" commented out in button1 and button2 event handlers, the DataGridView displays the "ID" column first when button1 is clicked and then it is not displayed when button2 is clicked ". It then is displayed as the first column when button one is clicked again. This is what I want to happen.

With "DataTable table = new DataTable();" not commented out in button1 and button2 event handlers, the DataGridView displays the "ID" as the first column when button1 is clicked and then it is not displayed when button2 is clicked". But it is displayed as the last column when button1 is clicked again. It remains the last column no matter how many times button1 and button2 are clicked. The textbox shows that the index of the "ID" column in the Table used as the data source remains zero whenever button1 is clicked and -1 when button2 is clicked.

Why is the display behaving differently in these two cases? I want to write code with the DataTable declared inside my methods like the second case.    See the code below: (copy the code into windows Form1 to see the problem)

        public Form1()
        {
            InitializeComponent();
          
        }
        DataTable table = new DataTable();
        private  void button1_Click(object sender, EventArgs e)
        {
            //DataTable table = new DataTable();
            dataSet1.Reset();
            table.Reset();
            dataSet1.Tables.Add(table);
            setTableForAccess(6, "Table1", dataSet1);
            bindingSource1.DataSource = dataSet1.Tables[dataSet1.Tables.IndexOf(table)];
            dataGridView1.DataSource = bindingSource1;
            textBox1.Text = dataSet1.Tables[dataSet1.Tables.IndexOf("Table1")].Columns.IndexOf("ID").ToString();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //DataTable table = new DataTable();
            dataSet1.Reset();
            table.Reset();
            dataSet1.Tables.Add(table);
            setTableForAccess1(14, "Table1", dataSet1);
           
            bindingSource1.DataSource = dataSet1.Tables[dataSet1.Tables.IndexOf(table)];
            dataGridView1.DataSource = bindingSource1;
            textBox1.Text = dataSet1.Tables[dataSet1.Tables.IndexOf("Table1")].Columns.IndexOf("ID").ToString();
        }

        public void setTableForAccess(int rowCount, string tableName,  DataSet dataSet1)//use to setup Access sourced DataSet//1/28/2016
        {
            rowCount -= 2; rowCount /= 2;//rowcount adjustment for Access data base
            for (int j = 0; j < rowCount; j++)
            {
                if (!dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("ID") || !dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("SentenceID") || !dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("Kanji" + j.ToString()) || !dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("Hiragana" + j.ToString()))
                {
                    if (!dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("ID") || !dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("SentenceID"))
                    {
                        dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Clear(); dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Rows.Clear();
                        dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Add(new DataColumn("ID", typeof(int)));
                        dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Add(new DataColumn("sentenceID", typeof(ulong)));
                    }
                    dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Add(new DataColumn("Kanji" + j.ToString(), typeof(string)));
                    dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Add(new DataColumn("Hiragana" + j.ToString(), typeof(string)));
                }
            }
        }
        public void setTableForAccess1(int rowCount, string tableName,  DataSet dataSet1)//use to setup Access sourced DataSet//1/28/2016
        {
            rowCount -= 1; rowCount /= 2;//rowcount adjustment for Access data base
            for (int j = 0; j < rowCount; j++)
            {
                if (!dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("SentenceID") || !dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("Kanji"+ j.ToString()) || !dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("Hiragana" + j.ToString()))
                {
                    if (!dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Contains("SentenceID"))
                    {
                        dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Clear(); dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Rows.Clear();
                        //dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Add(new DataColumn("ID", typeof(int)));
                        dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Add(new DataColumn("sentenceID", typeof(ulong)));
                    }
                    dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Add(new DataColumn("Kanji" + j.ToString(), typeof(string)));
                    dataSet1.Tables[dataSet1.Tables.IndexOf(tableName)].Columns.Add(new DataColumn("Hiragana" + j.ToString(), typeof(string)));
                }
            }
        }
        private void button3_Click(object sender, EventArgs e)
        {
            dataSet1.Reset();
        }

i use stored procedure to fill data in combobox and when the user open the form i want dont display just (----select----) when he click on this combobox the data display in C#

$
0
0
  CB_Driver_name.DataSource = clsParts.GET_ALL_DRIVER_NAME();
  CB_Driver_name.DisplayMember = "Driver_Name";
  CB_Driver_name.ValueMember = "Driver_ID";

why i am getting this error

$
0
0
<img alt="" src="https://social.msdn.microsoft.com/Forums/getfile/796870" />

How do I use my Data Table with 5 columns to populate my Listview with 5 columns?

$
0
0

My code below is not working, its producing this error "Object reference not set to an instance of an object." What it should do is retrieve values from my datatable and populate my listview. Any ideas what is wrong?

Sub fetch_DATABASE(ByVal getclass As String)
        'load database into datatable into listview

        Dim loadThisClass As String
        loadThisclass = getclass

        'load class data from MS access db
        Dim cnn As New OleDb.OleDbConnection
        Dim cmd As New OleDb.OleDbCommand
        Dim dataAdapter As New OleDb.OleDbDataAdapter
        cnn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=QuizDB.accdb"
        cnn.Open()

        With cmd
            .Connection = cnn
            .CommandText = "SELECT * FROM " & loadThisClass
        End With

        'create datatable
        Dim MyDataTable As New DataTable
        dataAdapter.SelectCommand = cmd

        'use dataAdapter values to fill the DataTable
        dataAdapter.Fill(MyDataTable)

        'loop through each row of the datatable and add to ListItem
        Dim MyDataRow As DataRow
        For i = 0 To MyDataTable.Rows.Count
            MyDataRow = MyDataTable.Rows(i)
            LVITEMS.SubItems.Add(MyDataRow("UserName").ToString())
            LVITEMS.SubItems.Add(MyDataRow("Score1").ToString())
            LVITEMS.SubItems.Add(MyDataRow("Score2").ToString())
            LVITEMS.SubItems.Add(MyDataRow("Score3").ToString())
            LVITEMS.SubItems.Add(MyDataRow("AverageScore").ToString())
        Next i

        'display in listview
        User_listView.Items.Add(LVITEMS)

    End Sub



Image Retrieving from sql to data gridview

$
0
0

Assalamu Alaikum

Please tell me how to retrieve image from sql database in to Datagridview in C# winform.

i have tried many time but  i m failed .

please help me in this regard


ODBC error during VS2005 to VS2013 migration

$
0
0

Hi Team,

We are currently migrating our projects from VS2005 to VS2013.

During this we got an error only at Windows Server 2008.

The same build working fine at Win 7 PC. 

Below is the stack Trace. Request you to help me ASAP

=================================================================================

System.Data.Odbc.OdbcException was caught
  ErrorCode=-2146232009
  HResult=-2146232009
  Message=""
  Source=""
  StackTrace:
       at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode)
       at System.Data.Odbc.OdbcDataReader.GetData(Int32 i, SQL_C sqlctype, Int32 cb, Int32& cbLengthOrIndicator)
       at System.Data.Odbc.OdbcDataReader.GetData(Int32 i, SQL_C sqlctype)
       at System.Data.Odbc.OdbcDataReader.internalGetInt32(Int32 i)
       at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i, TypeMap typemap)
       at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i)
       at System.Data.Odbc.OdbcDataReader.GetValues(Object[] values)
       at System.Data.ProviderBase.SchemaMapping.LoadDataRow()
       at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping)
       at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
       at System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
       at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet)
       at SJI.Common.DbHelper.ExecuteDataset(OdbcCommand& cmdExecute, Boolean clearCmdParams)
       at SJI.ViewsQ.DataLayer.OpenResultsetDAL.PopulateGrid_Queue(Int16& shtInpParam, Int16& shtOpParam, Boolean& blnShowMsg, Int16& shtProcNo, DataSet& dstSelectedData, ArrayList aylInpParam, ArrayList& aylOpParam) in C:\SJI\sjiapplication\sji\VS2005Src\views&queues\ViewsQ_DAL\OpenResultsetDAL.vb:line 103
  InnerException: 

Datagridview with footer

$
0
0

Greeting.

I have data shown from search queries in my datagridview. I want to add a line at the footer with the address of the company that the project is being made for. How can I do that. I need to show the footer when the pages are being printed.

I'm currently exporting the data to pdf and then printing them from there but if the footer can be set by any other way that i'm happy to change the printing settings. I would appreciate any sort of assistance in this problem.

Thanks

Sometimes Data grid view columns swap observed

$
0
0

I have a Datatable with 10 columns and displaying in datagridview with 5 columns with set displayindex as 0 to 4

Sometimes observed that last 2 columns are swaped. 

I am handling the below code for every data bind

dgvContacts.Datasource = null;

dgvContacts.Datasource =dtContacts

SetDisplayIndex();

Why Doesnt Databinding update the database?

$
0
0

Hello,

I followed tutorial on creating a Database and it has all gone very well, and i have 2 tables that are showing in my datasource. I dragged one onto a form and it created a datagridview and a databinding control at the top of the screen.

I then ran the project (F5) and voila my data appears in the datagrid.

I then click + to add a new record, and a newline is generated, i add the new line and press save !!!

It does not save the data. I close the project and check that table and 'no' the new record is lost.

I tried to update one field and press save and nothing once again.

The code is all pre generated and i have not amended or changed anything........ so why does it not save

Public Class Form1
    Private Sub CustomersBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles CustomersBindingNavigatorSaveItem.Click
        Me.Validate()
        Me.CustomersBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.SampleDatabaseDataSet)

    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: This line of code loads data into the 'SampleDatabaseDataSet.Customers' table. You can move, or remove it, as needed.
        Me.CustomersTableAdapter.Fill(Me.SampleDatabaseDataSet.Customers)

    End Sub
End Class

Thank you

[NET 4.0] Multilanguage Windows Forms MDI Application

$
0
0

Hello,

I Have a problem with creating multilanguage application. I found a lot of solutions to do that (ex. http://www.dotnetcurry.com/ShowArticle.aspx?ID=174) but that what i found doesn't work

with MDI forms, and toolbars. I works with DevExpress 10.2.

Can somebody help me resolve this problem ?

Best Regards

M.

How to Check if a value exist in a datagridview row and delete it.

$
0
0

How to Check if a value exist in a datagridview and if true; delete the whole row ?

 c# example please


karel

add new datagridview row to database

$
0
0
Writing in vb.net, I allow the user to add a new row to a datagridview.  On row leave, I validated to see if the appropriate cells have values, planning to insert the data into a database.    The last cell in the row is not populated when validated.   If I go back to the row, the cell is recognized.   The problem I have is that I update rows that exist and insert new rows.   If the user leaves a row without validation and then goes back, the new row in the database is not there to update. 

Sql exception unhandled a network related error whilst establishing a network

$
0
0

Hello

I am trying to connect c sharp project to the Sql database.I got the connection string from c sharp after  connecting to my database

however i get the error "Sql exception unhand-led a network related error whilst establishing a network".If i put my connection string with the server name and instance i get a red squiggly  line under my instance name .

What could be the cause and how do i rectify the problem .

Thank you


Visual Studio 2015. Properties Window doesn't allow to create or assign event for class property

$
0
0

I have control with class property MyClass.

MyClass have properties and events

For MyClass I set atribute [TypeConverter(typeof(ExpandableObjectConverter))] to allow expand it in the Properties Window at Design-Time.

Visual Studio allow to view and set properties of MyClass property and show events of MyClass property.

But it doesn't allow to assign or create event handler.

Events works as readonly properties.

Is this feature or bug of Visual Studio?

At the same time I can assign event handler at code without problem.

  dataGrid1.SearchBox.KeyDown += customersDataGridView_KeyDown;

Visual Studio 2015. Properties Window in Collection editor form doesn't allow to perfrom reset for the property.

$
0
0

Hi All

I have class in the collection with public property and 

    public int Width
    {
      get
      {
        if (widthStored)
          return width;
        else
          return DefaultWidth();
      }
      set
      {
        if ((widthStored == false) || (width != value))
        {
          widthStored = true;
          width = value;
          WidthChanged();
        }
      }
    }

    private bool ShouldSerializeWidth()
    {
      return (widthStored == true);
    }

    public void ResetWidth()
    {
      widthStored = false;
      WidthChanged();
    }

I can reset property Width in the standart Property list window

But I can't show Reset menu in the PropertyGrid of Collection editor Form.

How to make Reset menu work in Collection editor form.

Possible bug in transparent forms

$
0
0
I am working on an app with a transparent window.  I do the standard things such as create a background image, set the transparent key to match the background, set no border, etc.  If I set the BackgroundImageLayout to be "Center", I no longer get a transparent window.  If I leave the image as "Tile" then I do get a transparent window as expected (i.e. the window is non rectangular and looks just like my image file.)  I don't know why it should not work if the background image is "center".  So far, the best I can do is set the image to "tile" and then size the window, but this does not work if I want to be able to change skins.  Any suggestions?
Viewing all 2535 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>