not able to insert data in table using datatable - asp.net

i have one table having 3 rows and i am trying to insert data into first two rows using data table but it is inserting data like this , instead of inserting in first two row it is inserting in other rows
price qty total
--------------------
5 10 -
5 12 -
- - 50
- - 60
but i wants
price qty total
--------------------
5 10 50
5 12 60
i have used following code for selecting data from table than inserting data into table,it is showing data correctly but just inserting in wrong rows
int sp;
public DataTable bind1()
{
SqlConnection con = new SqlConnection("cnnection");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("select * from [order]", con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
public DataTable bind2()
{
SqlConnection con = new SqlConnection("cnnection");
con.Open();
SqlCommand cmd;
cmd = new SqlCommand("insert into [order](total) values(#total)", con);
cmd.Parameters.AddWithValue("#total", sp);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
return dt;
}
public void gbind()
{
DataTable dt = new DataTable();
dt = bind1();
DataTable dt1 = new DataTable();
DataColumn dc = new DataColumn("total");
dt1.Columns.Add(dc);
foreach(DataRow drow in dt.Rows)
{
int s1 = Convert.ToInt16(drow["price"]);
int s2 = Convert.ToInt16(drow["qty"]);
int s3 = s1 * s2;
DataRow dr = dt1.NewRow();
dr["total"] = s3;
dt1.Rows.Add(dr);
}
foreach (DataRow row in dt1.Rows)
{
string s1 = row["total"].ToString();
for (int i = 0; i < dt.Rows.Count; i++)
{
sp = Convert.ToInt16(s1);
dt = bind2();
}
}
i have tried like this also but still same problem
public void gbind()
{
DataTable dt = new DataTable();
dt = bind1();
foreach (DataRow drow in dt.Rows)
{
int s1 = Convert.ToInt16(drow["price"]);
int s2 = Convert.ToInt16(drow["qty"]);
int s3 = s1 * s2;
drow["total"] = s3;
sp = s3;
dt = bind2();
}
}

In your forEach loop in the gbind method, I don't think you should be adding a new row for "total", it would need to be a column. And dt1.Rows.Add(dr) should be dt1.Columns.Add(dr). Try rewriting your code to add a column instead. Let me know if that helps any.

Comment these two lines in your code. Remove the code to add extra rows. You just need to update the column value.
foreach(DataRow drow in dt.Rows)
{
int s1 = Convert.ToInt16(drow["price"]);
int s2 = Convert.ToInt16(drow["qty"]);
int s3 = s1 * s2;
//DataRow dr = dt1.NewRow();
dr["total"] = s3;
//dt1.Rows.Add(dr);
}

Related

How to convert a column that have integer values and string values i.e different currency 50 USD, 70 YEN, 34 CAD

Hello guys I have a table that checks the difference between dates and display as a label the difference bewteen the dates. After that I want to convert a column that have currency with integers and strings along them e.g 50 USD, 70 YEN, 34 CAD. I am interested to pull the column with currency value and multiply with the no. of days displayed by the label that captures the date difference then bind to another label that display the final results. Please any help on how to go about. Here is my sample code that fetches the date difference and after calucating it displays. When I try multiplying nothing displays on both labels
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "getBookIssuing";
cmd.Parameters.Add("#MemberId", SqlDbType.NVarChar).Value = txtMembeReturnId.Text.Trim();
cmd.Parameters.Add("#BookId", SqlDbType.NVarChar).Value = txtReturnBookId.Text.Trim();
cmd.Connection = con;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count >= 1) ;
{
//Calculate No. of Late Days
DateTime d1 = Convert.ToDateTime(DateTime.Now.ToString("yyyy/M/dd"));
DateTime d2 = Convert.ToDateTime(dt.Rows[0]["DueDate"].ToString());
string str= dt.Rows[0]["PenaltyRate"].ToString();
float x = Convert.ToSingle(str);
if (d1 > d2)
{
TimeSpan t = d1 - d2;
double latedaysno = t.TotalDays;
Labellatedays.Text = latedaysno.ToString();
double penalty = latedaysno * x;
Labelpenalty.Text = penalty.ToString();
}
else
{
Labellatedays.Text = "0";
Labelpenalty.Text = "0";
}
}
i think the issue rises when you retrieve the penaltyRate column
if you are sure that all the values came as [number][currency]
your code should probably look like this
string str= dt.Rows[0]["PenaltyRate"].ToString().Split(' ')[0];
float x = Convert.ToSingle(str);

Get Distinct data from datatable present in webservices using linq

I want to get only single row from multiple rows with same projectname from the datatable.(Eg. if we have two rows with same projectname,the datatable should be loaded with the only one row and neglect the other one.).I have been using webservices which has the datatable.
I want to achieve this functionality using linq.
I have pasted my code for datatable.Pls help me with working code.
[WebMethod]
public DataTable Get()
{
int a = 0;
cmd = con.CreateCommand();
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = " Select PROJECTNAME,COMPANY,PROJECTSTATUS,STARTEDIN,COMPLETEDIN FROM CMPPROJECT WHERE STATUS ='" + a + "'";
using (OracleDataAdapter sda = new OracleDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "CMPPROJECT";
sda.Fill(dt);
return dt;
}
}
}
You can create a DataView object which has a method ToTable in which you can pass true to parameter distinct to select distinct rows. But this has no sense to me. I would do this directly in a select query:
DataTable d = new DataTable("CMPPROJECT");
d.Columns.Add("PROJECTNAME");
d.Columns.Add("COMPANY");
d.Rows.Add(1, 1);
d.Rows.Add(1, 1);
d.Rows.Add(2, 2);
d = new DataView(d).ToTable("CMPPROJECT", true, "PROJECTNAME", "COMPANY");
Here is `linq solution:
var select = (from a in d.AsEnumerable()
select new { c1 = a["PROJECTNAME"], c2 = a["COMPANY"] }).Distinct().ToList();
d.Clear();
foreach (var item in select)
d.Rows.Add(item.c1, item.c2);

how to check in if condition it is string or not

in my search function i need to pass two parameters to SP.Here i kept if condition for that.But am not getting required output. here is my code.any one help me
if (IsValid)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("spRedemItem", con);
cmd.CommandType = CommandType.StoredProcedure;
if(Parameter.Equals(DropDownList2.SelectedValue=="CustomerCode"))
{
cmd.Parameters.AddWithValue("#CustomerCode", txtkey2.Text);
}
else
{
cmd.Parameters.AddWithValue("#CustomerName", txtkey2.Text);
}
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Session["CustomerName"] = dt;
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
Label10.Text = dt.Rows[0]["ItemCode"].ToString();
Label11.Text = dt.Rows[0]["CustomerName"].ToString();
Label12.Text = dt.Rows[0]["PointsNeeded"].ToString();
// Session["CustomerName"] = dt;
View.DataBind();
con.Close();
}
If your sproc has two parameters then you need to pass two parameters every time. Generally you would write your SQL code such that you can just pass NULL to any parameters that you want to ignore, e.g. WHERE (#Column1 IS NULL OR Column1 = #Column1). You then use DBNull.Value for the parameter value if you want to ignore that parameter. You can't use AddWithValue though, because a data type can't be inferred.
E.g.
command.CommandText = #"SELECT *
FROM MyTable
WHERE (#C1 IS NULL OR C1 = #C1)
AND (#C2 IS NULL OR C2 = #C2)";
command.Parameters.Add("#C1", SqlDbType.Int).Value = (someValue == "int"
? Convert.ToInt32(myTextBox.Text)
: (object) DBNull.Value);
command.Parameters.Add("#C2", SqlDbType.VarChar, 50).Value = (someValue == "string"
? myTextBox.Text
: (object) DBNull.Value);

need passing two parameters getting with one parameter value

This is my code. I am not able to get my desired output. I should pass parameters and retrieve either with CustomerCode or with CustomerName. Please help me. Thanks in advance and below I placed my sp
protected void txtsearch_Click2(object sender, EventArgs e)
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(myStr);
SqlCommand cmd = new SqlCommand("spRedemItem", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CustomerCode", SqlDbType.Int).Value =
(DropDownList2.SelectedItem.Text== "int" ? Convert.ToInt32(txtkey2.Text) :(object)DBNull.Value);
cmd.Parameters.Add("#CustomerName", SqlDbType.NVarChar, 50).Value =
(DropDownList2.SelectedItem.Text == "string" ? txtkey2.Text : (object)DBNull.Value);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
Session["CustomerName"] = dt;
con.Open();
DataSet ds = new DataSet();
sda.Fill(ds);
dt = ds.Tables[0];
Label10.Text = dt.Rows[0]["ItemCode"].ToString();
Label11.Text = dt.Rows[0]["CustomerName"].ToString();
Label12.Text = dt.Rows[0]["PointsNeeded"].ToString();
GridView1.DataBind();
con.Close();
}
--my sp
alter Proc spRedemItem
(
#CustomerCode int=null,
#CustomerName nvarchar(50)=null
)
as
begin
select b.ItemCode,a.CustomerName,c.PointsNeeded from CustomerProfMain a
left join tb_Product b on a.CustomerCode=b.ItemCode
left join tb_RedemptionProducts c on b.Product_ID=c.ID
where (#CustomerCode is null or CustomerCode=#CustomerCode) or (#CustomerName is null or CustomerName=#CustomerName)
end
Instead of using,
where (#CustomerCode is null or CustomerCode=#CustomerCode)
OR (#CustomerName is null or CustomerName=#CustomerName)
you can try changing your WHERE clause like,
where (#CustomerCode is null or CustomerCode=#CustomerCode)
AND
(#CustomerName is null or CustomerName=#CustomerName)

Exporting data from a table in SQL Server using ASP.Net

I am using Visual Studio 2010 and SQL Server 2008. I need to create a XML file which looks like:
<cat>
<name> "Categories"</name>
<link> "link"</link>
</cat>
The Categories and link values should be added from the database.
I have tried everything but I cannot get it to work. DO I have to create a XML file in ASP to do this?
These values are in the same table but there are other columns in the table as well.
My code looks something like this:
SqlCommand sqlcmd = new SqlCommand();
//sqlcmd.CommandText = "Select * from Categories";
DataSet ds = new DataSet();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("Select * from Categories", "Data Source=something;Initial Catalog=My Database;Integrated Security=True");
da.Fill(ds);
int rows;
rows = ds.Tables[0].Rows.Count;
int i;
for (i = 0; i <= rows - 1; i++)
{
string Categories = ds.Tables[0].Rows[i].ItemArray[0].ToString();
string address = "https://www.something.com/";
string link = address + ds.Tables[0].Rows[i].ItemArray[1].ToString();
}
ds.WriteXml(#"c:\output.xml", XmlWriteMode.WriteSchema);
Can someone please give me a detailed solution to this problem.
Thank you
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandText = "Select * from Categories";
DataSet ds = new DataSet();
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("Select * from Categories", "Data Source=something;Initial Catalog=My Database;Integrated Security=True");
da.Fill(ds);
int rows;
rows = ds.Tables[0].Rows.Count;
int i;
xmlwr.WriteStartElement("Cat");
for (i = 0; i <= rows - 1; i++)
{
xmlwr.WriteStartElement("name");
xmlwr.xmlwr.WriteString(ds.Tables[0].Rows[i].ItemArray[0].ToString());
xmlwr.WriteEndElement;
xmlwr.WriteStartElement("link");
xmlwr.xmlwr.WriteString(ds.Tables[0].Rows[i].ItemArray[1].ToString());
xmlwr.WriteEndElement;
}
xmlwr.WriteEndElement;
ds.WriteXml(#"c:\output.xml", XmlWriteMode.WriteSchema);

Resources