C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).

Share tech news, updates, or what's on your mind.

Sign up to Post

Can you please help me in that error?
Error in List Box[code]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InsertUpdateDel
{
    public partial class Form1 : Form
    {
        SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Lenovo\Documents\Visual Studio 2012\Projects\InsertUpdateDel\InsertUpdateDel\Database1.mdf;Integrated Security=True;User Instance=True");
        SqlCommand cmd = new SqlCommand();
        SqlDataReader sd;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
                cmd.Connection = cn;
                loadlist();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtID.Text != "" & txtName.Text != "")
            {
                cn.Open();
                cmd.CommandText = "Insert into info(id, name) values ('" +txtID.Text+"', '" +txtName.Text+"')";
                cmd.ExecuteNonQuery();
                cmd.Clone();
                MessageBox.Show("Record Inserted", "Programming");
                cn.Close();
                txtID.Text="";
                txtName.Text="";
                loadlist();
            }
        }
        …
0
Bootstrap 4: Exploring New Features
LVL 13
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

Can you please tell me what this error means?

Error statement: sd = cmd.ExecuteReader();

screenshot.JPG
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace InsertUpdateDel
{
    public partial class Form1 : Form
    {
        SqlConnection cn = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Lenovo\Documents\Visual Studio 2012\Projects\InsertUpdateDel\InsertUpdateDel\Database1.mdf;Integrated Security=True;User Instance=True");
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter sd;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
                cmd.Connection = cn;
                loadlist();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (txtID.Text != "" & txtName.Text != "")
            {
                cn.Open();
                cmd.CommandText = "Insert into info(id, name) values ('" +txtID.Text+"', '" +txtName.Text+"')";
                cmd.ExecuteNonQuery();
                cmd.Clone();
                MessageBox.Show("Record Inserted", "Programming");
                cn.Close();
                txtID.Text="";
                txtName.Text="";
                loadlist();
            }
        }

Open in new window

0
I have a List<A> listA a list of objects of type A. I want to make a new list. Is there any difference between the following:
given: List<A> listA
var List<A> newListA = new List<A>(listA);
var List<A> newListA = new List<A>(listA.ConvertAll((x) => (A)x));

Open in new window

I'm trying to figure out why some old code has this .ConvertAll in it and if it's necessary.
0
Hi,

How can I take the results of a Linq Query and convert to XML and save to file.

I have provided some same code below.

Thanks,
Ward

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Linq_Test_1
{

    class Person
    {
        public string Name;
        public int Age;
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Person> People = new List<Person>();

            Random rnd = new Random();

            for (int i=1;i<=100;i++)
            {
                Person person = new Person();

                person.Name = "Name" + i.ToString();                
                person.Age = rnd.Next(1, 101);
                People.Add(person);
            }

            int counter = 1;
            var results = from Person in People orderby Person.Age descending
                         select new
                         {
                             Name = Person.Name,
                             Age = Person.Age,
                             Index = counter++ 
                         };


        }
    }
}

Open in new window

0
I have a question regarding SQL permissions. I have a C# application that calls stored procedures. This application is wrapped around an ERP solution. This solution grants rights through a group. My stored procedures run fine on all the database that are part of the ERP solution. There is one stored procedure that runs against a database that is outside of the ERP solution. I have given user db_reader, db_writer and db_owner roles on the external database. These users are getting permission denied on this external database. What other role(s) must I give them? Is there something I need to grant on a table level?
0
I have a checkbox panel and I am adding the text for check box like this

chkPanel.Controls.Add(new CheckBox { Text = "Savings" + "This text needs to be red and bold", Checked = true, Enabled = false });
chkPanel.Controls.Add(new LiteralControl("<br />"));
chkPanel.Controls.Add(new CheckBox { Text = "Checking" , Checked = false, Enabled = false });


where you see "This text needs to be red and bold"  i actually want that text to be red and bold.  is it possible. if yes how?
0
I have two lists:
List<A> listA of objects A
List<B> listB of objects B

I also have a method which can take any pair of A and B and return a Boolean True or False:
bool TestAB(A a, B b)

Open in new window


Now I want to process all possible combinations of elements from listA and ListB,
for each pair {a, b} if TestAB(a, b) returns True then add element a to List<A> listApass, and add element b to List<B> listBpass. No duplicates in listApass or listBpass.


The other variation on this idea is if I have one listA of A elements and I want to process all possible pairs of elements from the same list (n things taken 2 at a time). This time I have a method TestAA(A a1, A a2) which returns a Boolean true or false, and I want to make a list of all pairs of elements for which the test is true (so I'd need a class which holds a pair of AA, we'll just call that class AA, it holds a pair of {a1, a2}, and we'll have a List<AA> listAA which is a list of all the pairs.)


(If that doesn't make enough sense, then here's how it would be done in CE# without Linq:
List<A> listA = new List<A>{ a1, a2, a3 }
List<B> listB = new List<B>{ b1, b2, b3 }

List<A> listApass = new List<A>();
List<B> listBpass = new List<B>();

foreach(A a in listA)
{
    foreach(B b in listB)
    {
        if (TestAB(a, b))
        {
            listApass.Add(a);  // but only if listApass does not already contain a
            listBpass.Add(b);  // but only if listBpass does not already contain b
        }
    }
}

Open in new window


I suspect there's a nice Linq way of doing this.

And for the second related question, the old C# code would be something like:
var listA = new List<A>{ a1, a2, a3 }
var listAA = new List<AA>();

for (int i=0; i < listA.Count; ++i)
{
    for (int j = i+1; j < listA.count; ++j)
    {
        if (TestAA(listA[i], listA[j]))
        {
            listAA.Add( new AA(listA[i], listA[j]) );
        }
    }
}

Open in new window

Again I assume this is something Linq would be well suited for. (I'm just not familiar with Linq yet.)
Thank you!
0
I have a C# ASP.NET Webform which fails on a Response.Redirect.  When I look at the resolved Url in variable myUrl it is "/WebForm1.aspx" whereas I would have expected that it would contain "C:/Users/PatClarke/source/repos/TiosClient/TiosClient". I am running this locally in debug mode. Why would ResolveUrl return Blank for the path ?


                try
                {
                    HttpContext.Current.ApplicationInstance.CompleteRequest();
                    string myUrl = ResolveUrl("~/WebForm1.aspx");
                    Response.Redirect(ResolveUrl("~/WebForm1.aspx"));
                }
                catch (Exception ex)
                {
                    MyGlobals.logger2.Information("Error encountered: {error} ", ex);

                }

Open in new window


The exception ex contains "ExceptionState = Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."

What am I doing wrong ? I have granted everyone permission to the directories in question.
0
Forgive my ignorance. I'm still learning xaml.

I have this button:
                <Button Name="CloseButton" DockPanel.Dock="Top" HorizontalAlignment="Right" Style="{StaticResource TitleBarButton}" Click="CloseButton_Click" Tag="Images/Window/close.png">
                </Button>

Open in new window

This is the style definition I have so far:
    <Style x:Key="TitleBarButton" TargetType="Button">
        <Setter Property="Width" Value="34"/>
        <Setter Property="Height" Value="26"/>
        <Setter Property="BorderBrush" Value="Transparent"/>
        <Setter Property="BorderThickness" Value="1,0,1,1"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border x:Name="border" Background="Transparent" BorderBrush="Transparent" BorderThickness="1,0,1,1" >
                        <Image Source="{Binding Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Button}}}" Stretch="None"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard>
                                    <Storyboard>
                                        <ColorAnimation Storyboard.TargetName="border" Storyboard.TargetProperty="Background.Color" To="#FFFFFCF4" Duration="0:0:0.2"/>
                          

Open in new window

1
Very complicated program here with Visual Studio 2017 in C#.

When I created the solution a default form came up.

I added a button.

What code, if any, would I add to the button click event to close the form?
0
CompTIA Network+
LVL 13
CompTIA Network+

Prepare for the CompTIA Network+ exam by learning how to troubleshoot, configure, and manage both wired and wireless networks.

Hi
In the code bellow I'm getting null because the profile path in the database can be  null

How do I test for this so it dosn't throw a  NullReferenceException

as can be seen in the picture person isn't null person.JPG

        public ActorBox(person person)
        {
            InitializeComponent();
            this.person = person;
            if( (person.profile_path.EndsWith( "JohnWayneBig.png")) || ( person.profile_path is null) )
            {
                ThumbPhotoPath = ImgPath + "JohnWayneSml.png";
                FullPhotoPath = ImgPath + "JohnWayneBig.png";

            }
            else
            {
                ThumbPhotoPath = ImgURL + "w45" + person.profile_path;
                FullPhotoPath = ImgURL + "original" + person.profile_path;
            }
            

            ThumbPictureBox.LoadAsync(ThumbPhotoPath);
            ActorNameLbl.Text = person.name;
        }

Open in new window



System.NullReferenceException
  HResult=0x80004003
  Message=Object reference not set to an instance of an object.
  Source=FilmsDB
  StackTrace:
   at FilmsDB.ActorBox..ctor(person person) in D:\Vb\MovieDB\FilmsDB\ActorBox.cs:line 34

Open in new window

0
I'm refactoring some legacy code.

The code has a class A, and a List<A> list of these items.

Elsewhere there is stored a List<int> list of integers. The integers are used to access elements from the List<A> list. Each integer is an index into the List<A>. So the integers act as pointers to elements of type A in List<A>.

I'm thinking there's got to be a better way, a more modern OOP way I can refactor this.

Given integer i from List<int>, it's not explicit that this is a pointer into List<A>. That's "god" knowledge that only the programmer knows.

I thought how about convert the List<int> into another List<A>, however I don't want to have 2 copies of the elements. (I already have that problem implicitly, as if List<A> changes, that could invalidate the contents of List<int>. List<A> needs to be one which can only grow, and never have elements removed.)

What would be a more OOP oriented design for this situation of wanting a subgroup of a List?

(Maybe it's OK to have two copies of the elements? One in the original List<A>, and the other in the sublist? It's not clear yet if the contents of A are invarient or might change.)
0
Hi!

After two hours in a support call, I could not figure out how to do something that every tech support article in cyberspace outlines to do in Crystal Reports, when you have to summarize a formula.  (Crystal won't let you do so, conventionally.)

I tried the variables where you conduct "x:= while printing records" but to no avail.

If anyone out there has had a challenge with this, please tell me what you did to overcome it.

As best as I can tell you and as best as I can remember from the support call, there is a formula in Group Footer #1 - not in Details - and I need to have a subtotal for this appear in Group Footer #2.

I created several "variable" formulas, I put them in this header, that header, this footer, that footer, the Report Footer, the Report Header, etc.

I did everything to the letter, but I still could not get a simple subtotal to appear.

Please help.

Thanks!

John
0
I am a C# newby with a recently upgraded Epicor software and need some help.

I need some code to put in a query and have no clue how to write it.  In the ABL language I was used to it would be something like this

If IsNull(LaborHed.PayrollDate) then Today
else LaborHed.PayrollDate

In my own words I want to check if a date field is blank or null.  If it is blank or null then put in today's date otherwise use the date in the field.
0
Hi. I read data from GPS using Serial port in C#. It is working ok.
 if I disconnected  GPS then gps information cannot be showed to user but something like "No data" have to be showing . Unfortunate I cannot find how to do that.
Nothing can be done here:
  public void SerialPort_DataReceivedAsync(object sender, SerialDataReceivedEventArgs e) // data received event from COM port
        {
   
            SerialPort port = (SerialPort)sender;
            _buffer = new byte[port.BytesToRead]; // byte count readable from COM port
            port.Read(_buffer, 0, _buffer.Length); // read data from COM port and fill out it into buffer
'''''''''''''''''''''''''''''''
}
or here
  public event DataArrivedHandler DataArrived // manager to add or remove event
        {


            add { lock (this) { _dataArrived += value; } }

            remove { lock (this) { _dataArrived -= value; } }
        }
How can I inform user that there is no GPS connection , not only when user connect to GPS but also when it is already connected?
0
The C# code below will grab user info, but I don't see a way to grab the first name or last name (which I believe is givenName and Surname).  I can grab things like the Name (which is username), SamAccountName, UserPrincipalName, etc., but I can figure out how to get the first or last name of the user. Can someone help? Thanks!

        private void button1_Click_1(object sender, EventArgs e)
        {
            string userName;
            string strUPN;
            bool isValid;
            List<string> allUsers = new List<string>();

            // define the OU container to search in
            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "MyDomain", "OU=MyDept,OU=MyUsers,dc=MyDomain,dc=local");

            // search for a UserPrincipal (user)
            UserPrincipal qbeUser = new UserPrincipal(ctx);

            // create your principal searcher passing in the QBE principal    
            PrincipalSearcher srch = new PrincipalSearcher(qbeUser);

            // find all matches
            foreach (var found in srch.FindAll())
            {
                // "found" is of type "Principal"
                userName = found.Name;
                strUPN = found.SamAccountName;
                allUsers.Add(userName + " " + strUPN);
            }
            MessageBox.Show(allUsers[499]);
        }
    }
}

Open in new window

0
I have a lengthy stored procedure that is called from my C# program. I have placed a label on the form and want that label to click up one second as long as the stored procedure runs. When it is done, I want to the label to disappear. How do I get this label to behave like a timer? Do I need to use backgrounder worker to accomplish this? Any sample code would be much appreciated.
0
Hi Folks, I'm integrating WPF in PS. though when I add a Progress Bar so it starts from 1 - 100 while trying to add the value to gradually fill the bar, it actually waits for the operation to conclude then display the 100% ... so it skips the animation.... According to the research I've done this weekend, it's behaviour is normal as this progressbar needs to run Synchronized with the WPF load..., does anybody body have any experience on how to fix the issue, or STAmultithreading...?
I know in WinForms a simple definition of the values and a performstep() would fix it

here's the code I'm working on it. Thanks for looking I know this is a very specific task...so I made as simple as possible. Thanks for looking in advance
[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')

[xml]$XAML = @'
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="247.857" Width="700">
    <Grid>
        <Grid.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF124F2E" Offset="1"/>
            </LinearGradientBrush>
        </Grid.Background>
        <Label Content="This is just a test" HorizontalAlignment="Left" Margin="265,17,0,0" VerticalAlignment="Top" Foreground="#FF72C196" 

Open in new window

0
Hi All

As mentioned in Internet, LiteDB dll can be used with Dot Net Framework 3.5 but I am facing issue while doing same though the LiteDB dll is working fine with framework 4.0. Can anyone guide on same?

I am trying to use DLL Version 4.1.4.0.

Thanks.
0
Starting with Angular 5
LVL 13
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

I have a table called Customers
which has CustomerID as PK and ParentCustomerID

Now, a single customer can have n number of sub or child customers
Also a sub or child customer can also have n level of customers.

So the customer's tree can go to n level deep.

In C# I can write a recursive method to get all child or sub customer.

But I in SQL I am trying to write a function which can return me sub customerId table till n level.
Do SQL server have recursive support or how can I get this list of customer.
0
I have a utility window that I open in a WFP C# project. One of the options allows a user to transfer a PO. To do that the user needs to enter a PO number. So I pop open another window. On this window I allow them to enter the PO number. I put an Exit button on that window. For some reason I cannot explain, when they click on the Exit button I get "Cannot access a dispose object" message. I am calling this window with the code below. The Exit button code to exit is below that.

Call window with this:

private void btnTransferPO_Click(object sender, EventArgs e)
{
    string TransferText = "Purchase Order";
    using (frmTransferWindow TransferWindowForm = new frmTransferWindow(TransferText))
    {
        if (TransferWindowForm.ShowDialog() == DialogResult.OK)
        {
            TransferWindowForm.Show();
            TransferWindowForm.Activate();
            TransferWindowForm.Focus();
        }
    }
}

Open in new window


Exit button has this code:

private void btnExit_Click(object sender, EventArgs e)
{
    this.Dispose();
    this.Hide();
}

Open in new window


What am I missing here? I have hundreds of other Exit that I close this way with no issues.
1
How could this be done with Linq?
The code loops through all a.b[i].c with index i.

Can i say: Give me a collection of all a.b[i].c for all i (index)?
0
I've code like below;

            if (CreateExcelFile(output_file))
            {
                var workbook = new ClosedXML.Excel.XLWorkbook(output_file);

// Additional to-do will list in here

                GenTplParams(workbook); //This writes something in excel

                workbook.SaveAs(output_file);
            }
        }

Open in new window



GenTplParams() is writing some values on that excel file from 3rd party tool and sometimes it can crash or thrown an error while processing and when i'm getting at the end a blank excel file.

But i'd like to get the file with already written values until the crash/error occurs also it'll give me an advantage to find out which value gives an error. I can easily read the excel file and check the last value and figure out the next value has a problem.

P.S. values are getting from 3rd party softwares COM objects.

Any help makes me glad. Thank you.
0
In my tool i have code like below to conditional formatting the cells as icons

if they are greater than 0 they will get green check icon, if cell value = 0 they will turn to yellow exclamation symbol and if they are below zero they should represent with red cancel icon.

But the problem is it doesnt effect the greaterthen value so my conditional formatting not works properly.

Picture2.png


Any help would be grateful.

Thanks.

        private void ConditionalFormatStatus(IXLWorksheet worksheet)
        {
            IXLCell first_cell = worksheet.Cell(2, 6);
            IXLCell last_cell = worksheet.Cell(worksheet.LastRowUsed().RowNumber(), 6);

            IXLRange range = worksheet.Range(first_cell.Address, last_cell.Address);

            range.AddConditionalFormat().IconSet(XLIconSetStyle.ThreeSymbols, false, true)
                .AddValue(XLCFIconSetOperator.EqualOrGreaterThan, 0, XLCFContentType.Number)
                .AddValue(XLCFIconSetOperator.GreaterThan, 0, XLCFContentType.Number);
            //.AddValue(XLCFIconSetOperator., 3, XLCFContentType.Number);
        }

Open in new window

0
I'm getting input string with format like below probably i need to change with char(10);

no mirror: 0[br]mirror:1

and i would like to write them in one excel cell like;

no mirror: 0
mirror:1

Picture1.png
0

C#

94K

Solutions

25K

Contributors

C# is an object-oriented programming language created in conjunction with Microsoft’s .NET framework. Compilation is usually done into the Microsoft Intermediate Language (MSIL), which is then JIT-compiled to native code (and cached) during execution in the Common Language Runtime (CLR).