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

XML Remove problem

$
0
0

Hi guys,

i have this XML file

<?xml version="1.0" encoding="utf-8"?><urlset><url><loc>http://www.mydomain.com/</loc><lastmod>2016-01-06T03:45:13+00:00</lastmod><changefreq>daily</changefreq><priority>1.00</priority></url></urlset>



 // Delete Record
        public void DeleteSitemap(string url)
        {
//passing "http://www.mydomain.com"
            XDocument sitemapData = new XDocument();
            sitemapData.Root.Elements("url").Where(i => (string)i.Element("loc").Value == url).Remove();

            sitemapData.Save(HttpContext.Current.Server.MapPath("~/Sitemap.xml"));
        }


///this code would delete if the Root
///<urlset> is as such;


However, if my XML is as such

<?xml version="1.0" encoding="utf-8"?><urlset  xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>http://www.mydomain.com/</loc><lastmod>2016-01-06T03:45:13+00:00</lastmod><changefreq>daily</changefreq><priority>1.00</priority></url></urlset>

The code wouldn't work anymore...

can anyone help me out?  I've been searching for hours.

thank you


Please do not forget to click “Vote as Helpful” if the reply helps/directs you toward your solution and or "Mark as Answer" if it solves your question. This will help to contribute to the forum.


Please could someone guide me in creating a new Datagridview correctly using c#

$
0
0

Hi There 

please be gentle as I'm a rank newbie (only been playing with c# for a year now as a hobbiest but loving it)

I have been battling for weeks now and finally decided to ask for help with this because I'm almost at the end of my tether and it seems like I'm in a long dark tunnel with no guiding light :-(.

First of all the original unbound Datagridview control I created in my form won't allow me to add ROWS , it used to work fine but now tell me I must add columns which I have go and have and had created manually on form loading. (Maybe I haven't set it up correctly in the first place :-( )

So I decided to start all over again and try to fathom the rather difficult to follow examples on the MSDN pages which seem to be a little over the top for someone starting out. I have combed through google and stackoverflow question texts blogs etc and it seems everyone has some different way of implementing and setting up a datagridview.

My use of it in the project I'm building is fairly simple I think :

The new datagridview needs to be unbound as I am not using a SQL database ( is this correct ? )

1.Create a datagridview which is easy to manage in terms of adding rows and columns as a user (either to be able to use ADD/REMOVE buttons or a right-click)

2.The user should be able to edit the rows (and of course re-order and delete or add new rows) -- I was able to do this as well as set columns to respond to a click and enable file browsing and selection as well as each cell having a combo box )

3. By clicking a button (the user should be able to export the values or each row to a CSV text file) -- I had this working to 

4. By clicking a button the user should be able import row values into a file (I had this working too)

WISH LIST ITEMS :

Some column headers should have a tickBox to set the value for all rows in that column. (I managed a tickBox in a single cell but not the whole column)

OK so at the moment I have a fully working project except for my damaged dataview, and am now starting to build a new datagridview in order to possibly fix the crashed one :-(

So the MAIN question is :

Could some kind soul please assist me in setting up the datagridview correctly and be prepared to answer a fair amount of questions  ?

I look forward to any replies and/or guidance.

D

0 Bound DataGridView is missing direction glyph on column click

$
0
0

Using standard winforms datagridview in .net 2.0.

DataGridView is bound to the BindingSource. BindingSource.DataSource is set to SortableBindingList.

Columns are created in my code and columns SortMode is set to DataGridViewColumnSortMode.Programmatic.

OnColumnHeaderClick I set multi-column sort with each column sort direction and glyph sorting order and refresh datagridview.

DataGridView gets sorted correctly but the column sort direction glyphs are gone.


BK

How to show the total in footer of the grid view

$
0
0

Hi 

Please how I can show the total price  as footer side of the grid view from the following code

 this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.Column1});
            this.dataGridView1.Location = new System.Drawing.Point(-7, 144);
            this.dataGridView1.Name = "dataGridView1";
            this.dataGridView1.RowTemplate.Height = 24;
            this.dataGridView1.Size = new System.Drawing.Size(1185, 435);
            this.dataGridView1.TabIndex = 0;



            DateTime datefrom;
            DateTime dateto;
            long invno;
            datefrom = this.dtpDateFrom.Value.Date;
            dateto = this.dtpDateTo.Value.Date;
            invno = 0;
            if (txtInvoice.Text != null && txtInvoice.Text != "" )
            {
                 invno = Int64.Parse(txtInvoice.Text);
            }        
        

            kmInvoice objKmInvoice = new kmInvoice();
            DataTable t = new DataTable();
            t = objKmInvoice.InvoiceList(datefrom, dateto,invno);
            dataGridView1.DataSource = t;

Please advise me how to show the total value of the invoice in footer of the fgridview


polachan

How to return HTML content from webbrowser control

$
0
0

Hello,

I try to catch the HTML code from a webpage after I have logged in to a page.
HTML is returned but that is the orignal HTML only BEFORE I logged in. For example I try to find "Log out" and other content in the string "getDocumentHTML" returned which exists on the webpage. But that can't be found.

How do we returned the final HTML content for the webpage after logging in?

Thank you!

private void button1_Click(object sender, EventArgs e)
        {
            String url = textBox1.Text;
            webKitBrowser1.Navigate("http://someloginURL.com");
        }
        private void webKitBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //This doesn't returnd the FINAL HTML content after a login to a webpage
            String getDocumentHTML = webKitBrowser1.DocumentText;
        }

DataBinding Won't Bind to Existing Property

$
0
0

So,

I've used databinding for all of my .Net life, and suddenly in 4.5.1 I am seeing these glitches and problems that are scaring me to a level of thinking that databinding has been fundamentally broken.

public partial class MainForm : Form, IReportProgress
{
    public MainForm()
        {
            InitializeComponent();
            this.Progress += MainForm_Progress;
        }

    private SProcRepository _sprocs;
    protected SProcRepository SProcs
    {
        get
        {
            if (_sprocs == null) _sprocs = new SProcRepository();
            return _sprocs;
        }
    }

    protected override void OnLoad(EventArgs e)
    {
        _spNameComboBox.DataSource = this.SProcs;
        _spNameComboBox.DisplayMember = "Name";
        try
        {
            Binding b = new Binding("Checked", this.SProcs, "UseGroups", true, DataSourceUpdateMode.OnPropertyChanged);
            _useCategoryCheckBox.DataBindings.Add(b);
        }
        catch (Exception ex)
        {//error: Cannot bind to the property or column UseGroups on the DataSource.//Parameter name: dataMember
        }
        base.OnLoad(e);
    }
}

public class SProcRepository : BindingList<SProcItem>
{
    public SProcRepository()
    {
        this.AddOnMissing = AddMissingBehavior.Always;
    }

    private bool _useGroups;
    public bool UseGroups
    {
        get { return _useGroups; }
        set
            {
                if (_useGroups != value)
                {
                    _useGroups = value;
                    this.UpdateFiles();
                }
            }
    }
}

Now this is something I've done for more than a decade, and suddenly, the DataBinding is throwing an error on binding a property.  The Source is just an object, and using reflection UseGroups is avalid property and yet DataBinding is claiming it isn't.

What's going on here?  I am sure it is probably some setting or tweak that is new to 4.5.1 (granted I have been using 3.51 for 5+ years, so the change to 4.5.1 will have nuances I haven't expected yet, but this was unexpected).

EDIT:

I have further investigated and it appears that because SProcRepository class the CurrencyManager is ignore properties that exist upon that instance, and focus solely upon the BindingList<T> T item.  and true UseGroups is not a property on SProcItem, but is a property on SProcRepository.  

So, I guess the question is, what changed or what do I need to do to get the DataBinding system to look at the "Object" I'm referencing not the "Objects Elements"?

Thanks

Jaeden "Sifo Dyas" al'Raec Ruiner


"Never Trust a computer. Your brain is smarter than any micro-chip."
PS - Don't mark answers on other people's questions. There are such things as Vacations and Holidays which may reduce timely activity, and until the person asking the question can test your answer, it is not correct just because you think it is. Marking it correct for them often stops other people from even reading the question and possibly providing the real "correct" answer.


How do you refresh data bound to a DataGridView

$
0
0

 

This should be easy... but I don't know how to do it.

I have created a DataSet that is bound to a DataGridView so that the DataGridView displays the data in my DataSet.  If my DataGridView is called dgvStudents, the following code DOES NOT do the job:

dgvStudents.Refresh();

I can see the grid itself flash and refresh(), but the data behind the grid is not being refreshed, so new items in the database (added by another process) are not being displayed in the grid.

How do you do this?

 

Binding data from a web service to a Windows Forms App

$
0
0

Hello,

I want to add a from a online web service, after I pasted the URL it displayed me the available service, and I created a service reference called ServiceReference1.  Now I don't know if this service can be bound to Form designer. If yes, how? 

Do I need to configure it manually in order to display data. The main intent on creating this windows form app is to display updated currency conversion rates in a table view.

I have searched online on how to do this , but I haven't found any successful article yet.

This is the first time that i try to get data from a web service, so I am a newbie on "web service for WinForms" .

Am I trying to do this in a totally wrong way? 

Here is the web service URL:

http://www.webservicex.net/CurrencyConvertor.asmx?WSDL



Admir


webkitbrowser keeps trying to login to a site but gets stuck at ...keep trying...

$
0
0

Hello,

I have a problem logging in to a site with the webkitBrowser control.

To mention is that logging in works in the standard: "webBrowser1" control in Visual Studio!

I am entering a "https://" webpage like this which I also wonder is the cause to the problem?

webKitBrowser1.Navigate("https://someurl.com");

On this page, I will login to a page with username and password. The process starts to login as usual as if I use chrome.

But it never succeeds to login and "tries forever" with the message:"We are running a few security checks. Please wait a few seconds."

It works to login with chrome but not with the webkitBrowser control. I use the webkitBrowser with default settings and wonder

if there is any type of setting that needs to be added etc that interfere with any type of security?

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;

HttpWebRequest returns only strange characters in the response

$
0
0

Hello,

I am trying to get the HTML from a page. When I use the below code I receive 170 KB of characters that looks like this:

"ɓdg   K  <? b"c~ C aH?aH 4"Or]"

I wonder if there is any wrong with the: Header, ContentType or Useragent etc?

See complete code:

                            String requestURL = "http://www.booking.com/searchresults.en-gb.html?aid=356982;label=gog235jc-region-XX-gr-poros-unspec-fr-com-L%3Aen-O%3Aunk-B%3Aunk-N%3Ayes-S%3Abo-U%3Asalo;sid=f2bb069850b01b677aee4d5e626cdccb;dcid=4;checkin_monthday=16;checkin_year_month=2016-01;checkout_monthday=17;checkout_year_month=2016-01;class_interval=1;csflt=%7B%7D;dtdisc=0;group_adults=2;group_children=0;hlrd=0;hyb_red=0;inac=0;label_click=undef;nha_red=0;no_rooms=1;redirected_from_city=0;redirected_from_landmark=0;redirected_from_region=0;region=3719;review_score_group=empty;room1=A%2CA;sb_price_type=total;score_min=0;si=ai%2Cco%2Cci%2Cre%2Cdi;src=searchresults;ss=Poros+Island;ss_all=0;ssafas=1;ssb=empty;sshis=0;ssne=Poros+Island;ssne_untouched=Poros+Island;track_sas=1;rows=15;offset=0";

                            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestURL);
                            request.Method = "GET";
                            request.Headers.Add("Accept-Encoding: gzip,deflate,sdch");
                            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
                            request.ContentType = "text/html; charset=utf-8";



                            String getHTML = String.Empty;
                            try
                            {
                                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                                {
                                    Stream dataStream = response.GetResponseStream();
                                    StreamReader reader = new StreamReader(dataStream);
                                    getHTML = reader.ReadToEnd();
                                    reader.Close();
                                    dataStream.Close();
                                }
                            }
                            catch (Exception ex) { MessageBox.Show(ex.ToString()); }


                            //Create file
                            StreamWriter writer = null; FileStream fs = null;
                            fs = new FileStream("C:/HTML.txt", FileMode.Create, FileAccess.Write, FileShare.ReadWrite); writer = new StreamWriter(fs);
                            writer.WriteLine(getHTML);
                            writer.Close(); fs.Close();

Problem to draw a vertical line to chart

$
0
0

Hello, 

I am using the chart component and tries to add a vertical line.

1. I first call "createchart()" to create 3 horizontal lines, which works fine.

2. I then call "createverticalline()" in order to Add a vertical line to the chart. No vertical line is shown in the chart which is the problem.

However, if I ONLY call "createverticalline()", then a vertical line is shown in the chart.

So the functions do work but I can't understand why the vertical line is not shown after I have"createchart()" ?

        private void button6_Click(object sender, EventArgs e)
        {
            createchart();
            createverticalline(); //Run ONLY this and a vertical line will be shown?
        }
        void createchart()
        {
            chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineColor = Color.Gainsboro;
            chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineColor = Color.Gainsboro;

            Series series = new Series(); int countlines = 0; DateTime dt = DateTime.Now;
            chart1.Series.Clear();
            for (int i = 1; i < 4; i++) //3 different lines
            {
                countlines++;
                series = new Series();
                series.Name = "Series" + countlines.ToString();
                series.Color = System.Drawing.Color.DarkBlue;

                series.IsVisibleInLegend = false;
                series.IsXValueIndexed = false;
                series.ChartType = SeriesChartType.Line;
                this.chart1.Series.Add(series);

                dt = DateTime.Now; dt = dt.AddDays(-1);
                for (int i2 = 0; i2 < 10; i2++)
                {
                    dt = dt.AddDays(1);
                    series.Points.AddXY(dt, (50 * i));
                }
            }

            DateTime minDate = DateTime.Now;
            DateTime maxDate = minDate.AddDays(8);
            chart1.ChartAreas[0].AxisY.Maximum = 200;
            chart1.ChartAreas[0].AxisY.Minimum = 0;
            chart1.ChartAreas[0].AxisX.Minimum = 0;
            chart1.Invalidate();
            chart1.ChartAreas[0].AxisY.RoundAxisValues();
            chart1.ChartAreas[0].AxisX.Title = "Date";
            chart1.ChartAreas[0].AxisY.Title = Foundcurrency;
            chart1.Series[0].XValueType = ChartValueType.DateTime; chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MM-dd";
            chart1.ChartAreas[0].AxisX.Interval = 1;
            chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Days;
            chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
            chart1.Series[0].XValueType = ChartValueType.DateTime;
            chart1.ChartAreas[0].AxisX.Minimum = minDate.ToOADate();
            chart1.ChartAreas[0].AxisX.Maximum = maxDate.ToOADate();
        }
        void createverticalline()
        {
            // Note that directly after adding points this will return NaN:
            double maxDataPoint = chart1.ChartAreas[0].AxisY.Maximum;
            double minDataPoint = chart1.ChartAreas[0].AxisY.Minimum;

            //the vertical line
            VerticalLineAnnotation annotation2 = new VerticalLineAnnotation();
            annotation2.IsSizeAlwaysRelative = false;
            annotation2.AllowMoving = true;
            annotation2.IsInfinitive = true;
            annotation2.Name = "myLine";
            annotation2.X = 0;
            annotation2.AxisX = chart1.ChartAreas[0].AxisX;
            annotation2.AxisY = chart1.ChartAreas[0].AxisY;
            annotation2.AnchorY = minDataPoint;
            annotation2.Height = maxDataPoint - minDataPoint;
            annotation2.Width = 2;
            annotation2.LineWidth = 2;
            annotation2.StartCap = LineAnchorCapStyle.None;
            annotation2.EndCap = LineAnchorCapStyle.None;
            annotation2.AnchorX = 1;  // <- your point
            annotation2.LineColor = Color.Red; // <- your color
            chart1.Annotations.Add(annotation2);
            chart1.Update();
        }


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

Datagridview Footer for printing

$
0
0

Thanks for reading this in advance.

I'm making a management system for a store and want to add their address in the datagridview. The data displayed in datagridview is exported to pdf and then printed.

How can I add the store address at the footer of the datagridview. Any kind of help will be highly appreciated.

Thanks

how to keep combo box as null before selecting the record , now always showing the first record in the combox item, without selection the record.

$
0
0

Even if I am not selecting  the item , In my combo box , always showing the  first record in the  in the combo box text. How can i keep it is null before selecting the record from ddwn. following is my code

 cmbCustomer.Items.Clear();
            kmInvoice objKmInvoice = new kmInvoice();
            DataTable t = new DataTable();
            t = objKmInvoice.CustomerList();
            cmbCustomer.DataSource = t;
            cmbCustomer.DisplayMember = "CustName";
            cmbCustomer.ValueMember = "Code";

Kind Regards

pol


polachan


IDataErrorInfo - DataGridView calls Error() but not item[] indexer

$
0
0

The item indexer never gets called so that the error icon won't ever get shown in the cell. Since the .Error() method gets called the row error icon does show. 

What is missing to enable the grid to call my indexer method show it will show the error?

In my form/user control i am setting up the grid:'

_radioItemsGrid.AutoGenerateColumns = false;

			_options.RadioButtons = new List<RadioButtonItem>();

			var bs = new BindingSource(_options.RadioButtons, null);
	        	_radioItemsGrid.DataSource = bs;

	        errorProvider1.DataSource = _radioItemsGrid.DataSource;


Here is my biz class

public class RadioButtonItem : IDataErrorInfo
	{
		public string Label
		{
			get { return _label; }
			set
			{
				if (_label != value)
				{
					_label = value;
					if(string.IsNullOrWhiteSpace(value))
						SetError(nameof(Label), "Label is required");
				}
			}
		}

		public string ModelExpression
		{
			get { return _modelExpression; }
			set
			{
				if (_modelExpression != value)
				{
					_modelExpression = value.Clean();
					if (string.IsNullOrWhiteSpace(value))
						SetError(nameof(ModelExpression), "Model Expression is required");
				}
			}
		}

		public string Error => _errors.Any() ? string.Join(Environment.NewLine, _errors.Select(e => e.Value).ToArray()) : "";

		private void SetError(string columnName, string errorMessage)
		{
			if(_errors.ContainsKey(columnName))
				_errors[columnName] = errorMessage;
			else
				_errors.Add(columnName, errorMessage);
		}

		private Dictionary<string, string> _errors = new Dictionary<string, string>();
		private string _label;
		private string _modelExpression;

		public string this[string columnName]
		{
			get
			{
				if (_errors.ContainsKey(columnName))
					return _errors[columnName];

				return string.Empty;
			}
		}

thanks!

webBrowser1: "Do you want to continue running scripts on this page" error

$
0
0

Hello,

I am navigating to an URL using the webbrowser1 control. When going to that URL, I get an error dialog that says:

"An error has occurred in the script on this page"

"Do you want to continue running scripts on this page"

Please see the screenshot of the dialogbox: http://www.bilddump.se/bilder/20160122032123-195.252.32.111.png

(Notice that the errorbox doesn't show in internet explorer)

|

The thing is that I need to run scripts in order for functions to work on the webpage I am going to. So I click "Yes" all the time

as this popup is coming up everytime I go to a new link on this webpage. But I cant keep clicking "Yes" all the time.

I have tried to put "webBrowser1.ScriptErrorsSuppressed = true;" like below. And yes, that takes away the dialog error box. 

But then the popups on this webpage doesn't show.

So I would need to "continue running scripts on this page" but how to prevent the dialog box to appear?

webBrowser1.ScriptErrorsSuppressed = true;







find occurences in data table certain columns

$
0
0

Hello People,


I have made a simple SQL Query that put the results in a data-table where I already prepared certain columns I have created.

there are 20 different columns.

there is order number in the column ”order number” (column 2).

I need a function that contains a loop that will perform the following function:

If an item exists twice in the column, regardless of row, the first instance must control all identical instances throughout. When an identical instance is identified, the content from the “target language” column in the first instance must be copied to the “target language” columns in all the other instances.

here is what I got so far this is a part of old code

[code VB.net]
  If HashDatatable1.Rows.Count > 0 Then
            For i As Integer = 0 To HashDatatable1.Rows.Count - 1
                If Not HashDatatable1.Rows(i).Item(18).ToString.Contains("Language:") Then
                    HashDatatable1.Rows(i)(18) = "0"
                End If


                '  MsgBox(HashDatatable1.Rows(i).Item(18).ToString())


            Next
        End If


Could someone help me with a code?

Thank you in advance



webBrowser1 control shows Empty popups

$
0
0

Hello,

I am using the webBrowser1 control.

I am navigating to a webpage and then I click on a link on that webpage which do produces a popupwindow in

the "real Windows Explorer browser". However this popup is completely blank/white. If I click on that link in the 

"real Windows Explorer browser" window, - then the popup shows as it should with text etc.

Why is the popup blank and empty?

I have tried to put this property to false and true with the same results:

webBrowser1.Navigate("http://someurl.com");

//I have tried both below
webBrowser1.ScriptErrorsSuppressed = false;
webBrowser1.ScriptErrorsSuppressed = true;

Windows Forms, VS2012, C# MDI and Access DataBase, problems connecting

$
0
0

I have a C# MDI application developed under VS2012 that works fine. I am trying to hook into a database and having problems. I have connected into the same database from 3 other apps, but they are 'standard' windows apps in C++, but also in VS2012. I get back a connect string from SQLDriverConnect which works fine in C++ but it and a zillion other strings from code samples get internal errors in C# on my OleDbConnection call. (Note: I only run the applications one at a time).

The application is tabbed MDI, NET framework 4 windows app.

Code:

       String strAccessConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\L drive\\PI Database\\Private_I.accdb;Persist Security Info=True;";

       OleDbConnection myAccessConn = null;

       try

       {

          myAccessConn = new OleDbConnection(strAccessConn);

       }

The error is:

'myAccessConn.ServerVersion' threw an exception of type 'System.InvalidOperationException'

The same happens when I change to:

        String strAccessConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\L drive\PI Database\Private_I.accdb;Persist Security Info=True;";

It is a forms application, and I connect to the database when opening first child form.


ert304

Viewing all 2535 articles
Browse latest View live


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