public dataset in C# - c#

i need to be able to save and retrieve data in a dataset in multiple places. i didnt want to copy and paste all my code since its pretty large, and i hope my super short version gets the idea across. thanks in advance. i currently have something along the lines of...
class program
{
DataSet ds;
static void main(...)
{
getMe(string);
}
public void getMe(string x)
{
ds = new mydataset();
DataRow dr = new ds.Tables[0].NewRow();
//blah blah add x to dr[ column ]
ds.Tables[0].Rows.Add(dr.ItemArray);
}
public void readMe()
{
**need to read dataset here with info added in rows from getMe()
}
}
EDIT:
edited DataSet = ds; to DataSet ds; to reflect my actual code.
if i call getMe(string) in my main, it errors with..."an object reference is required for a non-static field, method or property."
if i change getMe(string x) to public static void getMe(string) the error goes away but shows again for
ds = new mydataset();

Related

How to add a progressbar and status to a process that doesnt have a count like copying files does?

So i had posted a question on getting my sample project working and it now works.. Sample Project
And thats great because as in that example i have a production project that requires copying files, so that will work great for that one.
But this question is about displaying a progress bar to a process that im not clear on how to implement.
Im reading a excel file using closedxml, i read that file into a datatable in order to perform some filtering and other things in order to populate some listboxes on my form, how can my sample code in my other post be implemented against the creation of 5 or 6 data tables?
I can provide some of the datatable creation methods, but the over all code is close to 600 lines right now and not finished yet.. so below is a stripped down sample of the current code im working with..
private void sample()
{
string plink = #"C:\Test\Sizes.xlsx";
string[] DistinctDept = { "Dept Code", "Dept Description" };
DataTable ListDept = GetDistinctRecords(LoadExceltoDatatable(plink), DistinctDept);
ListDept.Columns.Add(new DataColumn("DeptCombo", typeof(string), "'('+[Dept Code] +') ' + [Dept Description]"));
if (string.IsNullOrEmpty(ListDept.Rows[0]["Dept Code"].ToString()))
{
ListDept.Rows[0].Delete();
ListDept.AcceptChanges();
}
lbDept.DataSource = ListDept;
lbDept.DisplayMember = "DeptCombo";
lbDept.ClearSelected();
}
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
public static DataTable LoadExceltoDatatable(string sizeoptcalc)
{
using (var wb = new XLWorkbook(sizeoptcalc, XLEventTracking.Disabled))
{
var ws = wb.Worksheet(1);
var foundMonth = ws.Search("Month", System.Globalization.CompareOptions.OrdinalIgnoreCase);
var monthRow = foundMonth.Last().Address; // A11
var lastcell = ws.LastCellUsed().Address; // BC3950
DataTable dataTable = ws.Range(monthRow, lastcell).RangeUsed().AsTable().AsNativeDataTable();
return dataTable;
}
}
Can this be changed to report the progress? I mean in some cases the excel files are large and do take some time to fill in my listboxes.
Here are more of the datatable creations that i would like to account for the overall progress of them

how to pass dataset as a parameter to another url in c#

private void import()
{
DataSet ds = new DataSet();
Export(ds);
}
[WebMethod]
public void Export(DataSet ds)
{
DataSet Ip_ds = new DataSet();
Ip_ds = ds; // insert this data in table
}
You dont need to pass a whole dataset as a parameter in the url .you can just pass the unique identifiers of the dataset as a parameter in the url and then use that identifier to get the required values.
Use HTTP POST method to post the data(Dataset) to the URL. You may need to use Newtonsoft JSON for serializing the Dataset.

n-tier c# applicaiton with BAL and DAL methods with exact same names ( signatures etc.. )

I'm on a project in which I'm failing to see the point of how a previous developer made decisions.
same exact method names in DAL and BAL
static is EVERYWHERE
what should i do with New methods to follow best practices?
example of existing code:
Calling appliction (could be console app or web app etc.. agnostic )
DataSet DS = CreditMgr.GetCreditRqstInfo(ddlGEO.Text);
BAL
public class CreditMgr
{
public static DataSet GetCreditRqstInfo(String GeoID)
{
try
{
DataSet DS = new DataSet();
DS = CreditIntfDB.GetCreditRqstInfo(GeoID);
return DS;
}
catch (Exception ex)
{
throw ex;
}
}
}
DAL
public class CreditIntfDB
{
public static DataSet GetCreditRqstInfo(String GeoID)
{
try
{
Database DB = new SqlDatabase(Common.ConnectionString);
String SQLCommand = Common.SPGetRqstInfo;
DbCommand DBCommand = DB.GetStoredProcCommand(SQLCommand);
DBCommand.CommandTimeout = Common.CommandTimeOut;
DB.AddInParameter(DBCommand, "#a_geo_id", DbType.String, GeoID);
DataSet DS = new DataSet();
DB.LoadDataSet(DBCommand, DS, new String[] { "CreditRqstInfo" });
return DS;
}
catch (Exception ex)
{
throw ex;
}
}
}
Yes, the whole point is to have layers of separation, but when the same method names are being used , and static, and each are simply doing the same exact thing with passing in string and returning a DataSet has "code smell" to me
Suggestions on better ways?
According to standard Object-Oriented Programming (OOP) design, your BAL classes should represent "things" that have some real world business meaning. Instead of having a CreditMgr that has a static method to get a CreditRqst, create a class CreditRequest that stores its own data (e.g. the DataSet), and preferably wraps it in some business-friendly manner (e.g. List of CreditLine or List of Account).
From there, you can either implement the Get method inside of CreditRequest, or you can turn CreditMgr into a service object (such as "CreditBureau", "Bank", "AccountsDesk", etc.), that has a method that takes a String GeoID and returns a CreditRequest.
In addition, using strings as keys (e.g. in GeoID) is smelly as well. Can you come up with something a little more strongly typed? You could create a class GeoID that enforces requirements (such as maximum length, allowable characters, checksum requirements, etc.)

NullReference Exception was unhandles

I'm having trouble when adding new team to the dataTable. VisualStudio is pointing at line teams.Rows.Add(dr) with NullReference error. Can you please help me?
private void addTeam(String nazwa)
{
DataRow dr = players.NewRow();
//dr["playerID"] = nazwa;
dr["nazwa"] = nazwa;
teams.Rows.Add(dr); //<--there is en error
}
class Program
{
static DataTable players ;
static DataTable teams;
private DataSet teamMenager;
static void Main(string[] args)
{
The DataTable is not yet initialized
static DataTable teams;
You can initilaize it for example with the default constructor:
static DataTable teams = new DataTable();
static DataTable players = new DataTable();
Although it's not clear why you made them static. This would mean that every instance of Program would share the same DataTable which can be problematic with multiple threads since you need to provide a locking mechanism. Just remove the static and create an instance of Program:
static void Main(string[] args)
{
Program p = new Program();
p.Start(); // open your form(s) there and add teams or what else
// ...
Edit: There's something else wrong. You're creating the new DataRow via players.NewRow but adding it to the DataTable teams. That is not allowed. Every DataRow belongs to one DataTable. That cannot be changed and will result in an ArgumentException.
DataRow dr = players.NewRow();
dr["nazwa"] = nazwa;
so add it to players instead:
players.Rows.Add(dr); //<--there is en error

Visual C# Dataset to Class

I am a student programer working in Visual Studios C# and I am trying to access information from my dataset and insert the data into a class. This is not, by any means, homework I've just have some personal projects I've been wanting to try. I have tried several approaches that have been mentioned on this site; however, no information is displayed. My code looks similar to this:
class MyClass
{
public string ColumnData1
{
get; set;
}
public int ColumnData2
{
get; set;
}
public string Display()
{
string MyString = ColumnData1 + ColumnData2.ToString();
return MyString;
}
}
I use this to insert data into class:
private void MyForm_Load(object sender, EventArgs e)
{
MyDataSet.MyDataTable MDT = new MyDataSet.MyDataTable();
List<MyClass> MyList = new List<MyClass>();
foreach (DataRow MyDataRow in MDT.Rows)
{
Mylist.Add(new MyClass()
{
ColumnData1 = (string)MyDataRow["Data1"],
ColumnData2 = (int)MyDataRow["Data2"]
{
}
Lastly to display the information:
textBox1.Text = Mylist[0].Display();
}
In the end, however, nothing ends up displaying. This also wasn't the only thing I've tried to display the information.. it's like the information doesn't exist. I don't receive any errors and when I try to add a "Stop Point" at the insertion part of the code it just skips it. I should mention also that I have many text boxes and list boxes that pull data off the database just fine, of course Visual Studios binds those for me. Any help is very much appreciated.
Edit:
Ok, excluding the new data table. If I had an existing dataset how would I would I use it to fill my class.
That's normal because your DataTable is empty (Your create instance)
MyDataSet.MyDataTable MDT = new MyDataSet.MyDataTable();//<------Empty
foreach (DataRow MyDataRow in MDT.Rows)
{
....
}
Fill DataSet :
string queryString =
"SELECT .... FROM YourTable";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "NameOfDataSet");
You must have some data in MDT before you insert it in the MyList, List of MyClass.
Declaration without data:
MyDataSet.MyDataTable MDT = new MyDataSet.MyDataTable();

Categories

Resources