I have created a table code and would like to search and retrieve an answer introducing device IMEI in TextBox IMEI und when I click on the search, I want to display the result code_mck in the textbox code i want display the result:
id Imei code_mck
1 356885021519453 830782136
2 356885021519156 948790617
3 356885021518893 715398945
4 356885021518935 567456626
5 359654022104377 557960750
Initially I have a typical three-layer architecture and the search method is in the Data Layer. I have some trouble with my SQL Query:
public DataSet recherche(string code)
{
DataSet ds = null;
using (OleDbConnection cnn = new OleDbConnection(strConn))
{
cnn.Open();
string Oledb = "SELECT * FROM Code WHERE Imei=#IMEI";
using (OleDbDataAdapter adapter = new OleDbDataAdapter(Oledb, cnn))
{
adapter.SelectCommand.Parameters.AddWithValue("#IMEI", code);
ds = new DataSet();
adapter.Fill(ds, "Code");
}
}
return ds;
}
Business Logic layer:
namespace unlock2_buisness
{
public class code_imei
public DataSet rechercheduCode(string imei)
{
unlockDAL objetDataLayer = new unlockDAL();
if (imei == "")
throw new Exception("merci d'indique l'imei de recherche");
DataSet dt = null;
dt = objetDataLayer.recherche(imei);
return dt;
}
In my User Layer, the TextBox dedicated for search to display the result in textbox code is not responding, and am not getting the appropriate code by providing the device IMEI as it should be from the table.
private void btnrechercheimei_Click(object sender, EventArgs e)
{
imeiLogic.rechercheduCode(txtimei.Text);
imeiLogic.rechercheduCode(txtcode.Text);
}
I will appreciate your support.
The problem is how you use your BusinesLogic class.
public DataSet rechercheduCode(string imei) takes a string as input parameter and returns a DataSet.
When you call the method like this:
imeiLogic.rechercheduCode(txtimei.Text);
you do provide the input parameter (the value that is in textbox) but you don't store the returned Dataset in a variable.
The dataset wil have a table called Code that will hold the result rows from the query or 0 rows if nothing is found.
Staying as close as possible to your current implementation I suggest this:
private void btnrechercheimei_Click(object sender, EventArgs e)
{
// call the BLL to get a dataset
var dataSet = imeiLogic.rechercheduCode(txtimei.Text);
// get our table in the dataset
var codeTable = dataSet.Tables["Code"]; // table
// check if there was a row returned
if (codeTable.Rows.Count > 0)
{
var row = codeTable.Rows[0]; // pick the first one
txtcode.Text = row["code_mck"].ToString(); // update our textbox
}
// Add handling for 0 rows and/or more than 1 rows returned
}
Related
I'm developing auction site as my University Final year project.
But I'm stuck in one problem i-e Which I click "View Details" hyperlink in Grid-view, it should compare Sno and Display its complete information present in SQL Server Table in new Tab.
Screenshot of Grid-view
string query1 = "select * from Sell ";
What condition I should apply in the above SQL Query to perform my task
If I understand you question, it sounds like you are wanting to have a link view details link clicked that retrieves the data from you sql database for the specific item being clicked.
If this is the case you are first going to want to get your sql data into a string which takes a couple more steps then what your are attempting in your example.
Instead try using a stored procedure which takes a parameter being the item your fetching and use this model:
public string StringFromDatabase()
{
SqlConnection connection = null;
try
{
var dataSet = new DataSet();
connection = new SqlConnection("Your Connection String Goes Here");
connection.Open();
var command = new SqlCommand("Your Stored Procedure Name Goes Here", connection)
{
CommandType = CommandType.StoredProcedure
};
var dataAdapter = new SqlDataAdapter { SelectCommand = command };
dataAdapter.Fill(dataSet);
return dataSet.Tables[0].Rows[0]["Item"].ToString();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (connection != null)
{
connection.Close();
}
}
}
This is my First report using SSRS.
I am trying to generate a Report using SSRS in asp.net.
My Need is:
I want to create a report with multiple tables (4 tables) that have relationship with one another. I have configured each individual table with accepting 1 parameter, for instance:
What I tried is:
I have created a dataset.xsd with 4 tables and given the relationship between those tables.
Then I created a report.rdlc and designed a report with four tables and drag and dropped the required field to the table and created a report parameter called ID.
The error i'm Getting is:
A data source instance has not been supplied for the data source 'DataSet2'
What I have written in cs page on button click is:
protected void BtnGo_Click(object sender, EventArgs e)
{
DataSet2TableAdapters.TB_TransReceiptTableAdapter ta = new DataSet2TableAdapters.TB_TransReceiptTableAdapter();
DataSet2.TB_TransReceiptDataTable dt = new DataSet2.TB_TransReceiptDataTable();
ta.Fill(dt,Convert.ToInt16( TxtID.Text));
//ta.Fill(dt,TxtID.Text);
ReportDataSource rds = new ReportDataSource();
rds.Name = "DataSet2";
rds.Value = dt;
ReportParameter rp = new ReportParameter("ID", TxtID.Text.ToString());
rptviewer.LocalReport.DataSources.Clear();
rptviewer.LocalReport.ReportPath = "Report1.rdlc";
rptviewer.LocalReport.SetParameters(new ReportParameter[] { rp });
rptviewer.LocalReport.DataSources.Add(rds);
rptviewer.LocalReport.Refresh();
rptviewer.Visible = true;
}
The help i seek is:
I dont know how to bind the report via code, since I have four tables that are related to one another with foreign key. Above is the code I used but it throws an error.
I would be very thankful if some one could help me to solve this issue.
Thanks in advance.
As per tgolisch instead of table i Bound dataset and passed to report it works fine.
And also instead of four separate table i created a view .It Makes my job simple
private DataTable getData()
{
DataSet dss = new DataSet();
string sql = "";
sql = "SELECT * from VW_TransReciptReport WHERE tREC_NUPKId='" + TxtID.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
da.Fill(dss);
DataTable dt = dss.Tables[0];
return dt;
}
private void runRptViewer()
{
this.rptviewer.Reset();
ReportParameter rp = new ReportParameter("ID", TxtID.Text.ToString());
this.rptviewer.LocalReport.ReportPath = Server.MapPath("ReportReceipt.rdlc");
rptviewer.LocalReport.SetParameters(new ReportParameter[] { rp });
ReportDataSource rdsB = new ReportDataSource("DataSet1_VW_TransReciptReport", getData());
this.rptviewer.LocalReport.DataSources.Clear();
this.rptviewer.LocalReport.DataSources.Add(rdsB);
this.rptviewer.DataBind();
this.rptviewer.LocalReport.Refresh();
}
using C#, .net framework 4.5, VS 2012
Try to create simple relation between tables in data set, but got System.NullReferenceException, as I can see on MSDN, it's mean occurs when you try to reference an object in your code that does not exist. But, think i create all required objects.
My code below:
//create place for storing all tables from data base
private DataSet myDS = new DataSet("AutoLot");
//command builders for easy way access to tables
private SqlCommandBuilder sqlCInventory;
private SqlCommandBuilder sqlCOrders;
private SqlCommandBuilder sqlCCustomers;
//adapters for each table
private SqlDataAdapter sqlAInventory;
private SqlDataAdapter sqlAOrders;
private SqlDataAdapter sqlACustomers;
//connection string
private string cnStr = string.Empty;
public MainForm()
{
InitializeComponent();
//get connection string from .config file
cnStr =
ConfigurationManager.ConnectionStrings["AutoLotSqlProvider"].ConnectionString;
//create adapters
sqlACustomers = new SqlDataAdapter("Select * From Customers", cnStr);
sqlAInventory = new SqlDataAdapter("Select * From Inventory", cnStr);
sqlAOrders = new SqlDataAdapter("Select * From Orders", cnStr);
//automatic generate commands
sqlCCustomers = new SqlCommandBuilder(sqlACustomers);
sqlCInventory = new SqlCommandBuilder(sqlAInventory);
sqlCOrders = new SqlCommandBuilder(sqlAOrders);
//add table to data Set
sqlAInventory.Fill(myDS);
sqlAOrders.Fill(myDS);
sqlACustomers.Fill(myDS);
//create relationship between tables
BuildTableRelationShip();
//create DataSourse for datGrids on UI
dataGridViewCustomer.DataSource = myDS.Tables["Inventory"];
dataGridViewOrders.DataSource = myDS.Tables["Orders"];
dataGridViewCustomer.DataSource = myDS.Tables["Customers"];
}
and here I got exception
private void BuildTableRelationShip()
{
//create object of relationShips
DataRelation dr = new DataRelation("CustomersOrders", //name of relation
myDS.Tables["Customers"].Columns["CustID"], //main columns
myDS.Tables["Orders"].Columns["OrderID"]); //related columns
myDS.Relations.Add(dr);
//second relation
dr = new DataRelation("InventoryOrder",
myDS.Tables["Inventory"].Columns["CarID"],
myDS.Tables["Orders"].Columns["OrderID"]);
//add relations to dataset
myDS.Relations.Add(dr);
}
Why i got this Null reference Exception? What i miss?
EDIT
You should call fill on individual DataTables rather than the whole DataSet.
sqlAInventory.Fill(myDS);
sqlAOrders.Fill(myDS);
sqlACustomers.Fill(myDS);
would become
sqlAInventory.Fill(myDS, "Inventory");
sqlAOrders.Fill(myDS, "Orders");
sqlACustomers.Fill(myDS, "Customers");
This method will automatically add a table to your DataSet if it doesn't exist, and populates it with data if it does. MSDN has more information on this method of the fill.
I am developing an ASP.Net C# Web Application that contains a GridView to display the records of a certain table from my database which I use ODBC Connection to connect to it and a DataSet to save data in it and edit it then I should save data to the database using the changes made in the DataSet.
I could access the database succefully using the fill() method of the OdbcDataAdapter and I could do databinding so that the data is viewed in the GridView.
My question is how I can save the gridview to the dataset then to the database when any updates or changes done [the vice versa of the operation done before]?
My sample code that is used inside a web form class is as follow:-
private void SelectFromDatabase()
{
string OdbcConnectionString1 = getConnectionString();
OdbcConnection OdbcConnection1 = new OdbcConnection(OdbcConnectionString1);
string OdbcSelectText1 = "SELECT * FROM table";
OdbcCommand OdbcSelectCommand1 = new OdbcCommand(OdbcSelectText1, OdbcConnection1);
OdbcDataAdapter OdbcDataAdapter1 = new OdbcDataAdapter();
try
{
OdbcConnection1.Open();
OdbcDataAdapter1.SelectCommand = OdbcSelectCommand1;
OdbcDataAdapter1.AcceptChangesDuringFill = true;
int FillResult = OdbcDataAdapter1.Fill(myDataSet, TableName);
myDataSet.AcceptChanges();
fillGridViewbyDataset(myGridView, myDataSet, TableName);
Response.Write("<br/>SelectFromDatabase() Fill Result: " + FillResult);
}
catch (Exception Exception1)
{
Response.Write("<br/> SelectFromDatabase() Exception: " + Exception1.Message);
}
finally
{
OdbcConnection1.Close();
}
}
private void fillGridViewbyDataset(GridView gv, DataSet ds, string dt)
{
gv.DataSource = ds;
gv.DataMember = dt;
gv.DataBind();
}
what I need is something like:-
how to save Gridview to the DataSet then save the DataSet to the database as i got the gridview updates but the database still without any updates !!
if I have a DataSet called myDs and I edit a field in it by direct access in a loop like the following:-
for (int i = 0; i < myDS.Tables[TableName].Rows.Count; i++)
{
//some function or web method to get the id value of the record being updated
int n = getNewNumber();
//updating the dataset record according to some condition
if (n == 0)
{
myDS.Tables[TableName].Rows[i]["id"] = n;
myDS.Tables[TableName].Rows[i]["description"] = "some data";
}
else
{
myDS.Tables[TableName].Rows[i]["id"] = n;
myDS.Tables[TableName].Rows[i]["description"] = "new data";
}
}
How I make these changes done in the database as I could see it in the GridView when I do databind() but the database is not affected and I try using the fill & update methods of OdbcDataAdapter and OdbcCommandBuilder ??
Please this is urgent as I need it in developing an important application..
Thanks in advance for your replies and answers .....
Everything you need to know about saving from the GridView to the DataSet and to the DB is explained is this article.
Hope this helps!
If it's "an important application", I'd recommend using Stored Procedures and grant only the EXECUTE privilege to the database user on the package. If the user has full DML privileges, your data might be more vulnerable.
Here's a basic tutorial on calling stored procedures
If you have time, I'd also look at the Microsoft Enterprise Library.
At present i have a the following code populating a datagridview showing the user account information on our system. What i want to do do is have a checkbox on the datagridview for the option "accountenabled" and a update button at the bottom of the form so it will update all users that have had changes made against them. I am currently pulling the data back using an sqldatareader however from what i have read i need to use a sqldataadapter. I`ve created the column names on the datagridview and the reader is currently pulling everything back correctly.
Could someone please point me in the right direction of doing this with an sqldatadapter?
Thanks
public UserAdmin()
{
InitializeComponent();
//Load user list
// Locals
Functionality func = new Functionality();
SqlConnection supportDB = null;
SqlCommand CheckUser = null;
SqlDataReader rdr;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
string User = System.Environment.UserName.ToString();
string spName = "gssp_ShowAllUsers";
try
{
using (supportDB = new SqlConnection(GSCoreFunc.ConnectionDetails.getConnectionString(ConnectionType.SupportDB)))
{
using (CheckUser = new SqlCommand(spName, supportDB))
{
// Set the command type
CheckUser.CommandType = CommandType.StoredProcedure;
// Populate the parameters.
CheckUser.Parameters.Add(func.CreateParameter("#spErrorID", SqlDbType.Int, ParameterDirection.Output, DBNull.Value));
// Open the connection and populate the reader with the SP output
supportDB.Open();
rdr = CheckUser.ExecuteReader();
if (CheckUser.Parameters["#spErrorID"].Value != null)
{
throw new InvalidOperationException();
}
// If the data reader has rows display output on label
if (rdr.HasRows)
{
//Output values
while (rdr.Read())
{
//Bind to data table
dgvUsers.Rows.Add(rdr["agentID"].ToString(), rdr["createdon"].ToString(), rdr["firstname"].ToString(), rdr["lastname"].ToString(), rdr["username"].ToString(), rdr["emailaddress"].ToString(), rdr["Departments"].ToString(), rdr["accountenabled"].ToString(), rdr["AgentAccountLevel"].ToString());
}
}
// Close reader and connection.
rdr.Close();
supportDB.Close();
}
}
}
catch (Exception ex)
{
//Show error message
string error = ex.ToString(); //Real error
string FriendlyError = "There has been error loading the user list"; // Error user will see
GSCoreFunc.ShowMessageBox.msgBoxErrorShow(FriendlyError);
//Log error to ExceptionDB
GSCoreFunc.ReportException.reportEx(GSCoreFunc.ApplicationInformation.ApplicationName, error, FriendlyError, GSCoreFunc.ApplicationInformation.ComputerName, GSCoreFunc.ApplicationInformation.OperatingSystem, GSCoreFunc.ApplicationInformation.screenSize, GSCoreFunc.ApplicationInformation.IPAdddress, GSCoreFunc.ApplicationInformation.domainName);// Pass error to GSCoreFunc to log to the ExceptionDB
}
}
private void btClose_Click(object sender, EventArgs e)
{
//Close window
Close();
}
}
}
There is nothing wrong with using the SqlDataReader. The SqlDataAdapter is a higher level api that allows you to iterate through an SqlDataReader and store a copy of the results in a DataTable or a DataSet. This copy can then be used as the data source for your DataGridView.
One thing I would change with your code would be to use data binding instead of generating each row manually. If you set the DataSource property of the grid to either your SqlDataReader or to a DataTable filled by an SqlDataAdapter and then call the grids DataBind() method the grid should be filled automatically with your data.
To control the columns you would make sure your query only returns the required columns, and you would define the column setup in your aspx-file.
Using data binding is generally an easier and more flexible approach, so you should consider using that instead.
Look at this code
Initialize a sql adapter and fill with data source . Use a connection string other than using sql data source because it would be easy for customizing. :)