changing label text on selectedindexchanged of dropdown - asp.net

I need the address (below the dropdown) to change as per the name that is selected in the dropdown... (they are all for one user only)...! (i donno why this keeps saying your post seems only code!!!!!!)
public DataSet BindDropDownListToAUserAddress2()
{
UserFunctions objGetSession = new UserFunctions();
string strSession = objGetSession.GetEmailFromSession();
DataSet dsUserAddress = new DataSet();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
con.Open();
string strQuery = "(SELECT FirstName +' '+ LastName as FullName, * FROM AUserAddress inner join AState on AUserAddress.State_ID = AState.ID inner join ACountry on AUserAddress.Country_ID = ACountry.ID inner join AUser on AUserAddress.AUser_ID=AUser.ID where AUser.Email='" + strSession + "')";
SqlCommand cmd = new SqlCommand(strQuery, con);
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(dsUserAddress, "AUserAddress");
con.Close();
return dsUserAddress;
}
protected void ddlName_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet dsUserAddress = objBindDDL.BindDropDownListToAUserAddress2();
string strSession = objGetSession.GetEmailFromSession();
ddlName.SelectedValue = "FullName";
if (objBindDDL.BindDropDownListToAUserAddress2() != null && objBindDDL.BindDropDownListToAUserAddress2().Tables.Count > 0)
{
lblDisplayFirstName.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["FirstName"].ToString();
lblDisplayLastName.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["LastName"].ToString();
lblDisplayAddressLine1.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine1"].ToString();
lblDisplayAddressLine2.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine2"].ToString();
lblDisplayAddressLine3.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["AddressLine3"].ToString();
lblDisplayCity.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["City"].ToString();
lblDisplayState.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["StateName"].ToString();
lblDisplayCountry.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["CountryName"].ToString();
lblDisplayPostalCode.Text = dsUserAddress.Tables["AUserAddress"].Rows[0]["PostalCode"].ToString();
}
}

when you are binding data to dropdown list
ddlStatus.DataTextField = "FullName";
ddlStatus.DataValueField = "Id";
onselected index change event
int ID =Convert.Toint32(ddlName.SelectedValue)
by using this ID select only this ID Record from the dataTable and display

Related

Insert records in database in which have 3 foreign keys

I'm trying to insert a record in the table but the problem is in that table have 3 foreign keys. I'll be using dataTable for that but it gives an error 'There is no row position at 0'
                             
There is my code:
try
{
using (var sqlConnection = new Helpers.SqlConnectionHelpers())
{
var connection = sqlConnection.OpenConnection();
command = new SqlCommand("CarSold_Insert", connection);
command.CommandType = CommandType.StoredProcedure;
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = '" + txtPrice.Text + "'", connection);
DataTable table = new DataTable();
DataSet dataSet = new DataSet();
table.Load(commandTwo.ExecuteReader());
var carForSaleId = table.Rows[0]["CarForSaleId"].ToString();
var userId = table.Rows[0]["UserId"].ToString();
var salesPersonId = table.Rows[0]["SalesPersonId"].ToString();
command.Parameters.AddWithValue("CarForSaleId", carForSaleId);
command.Parameters.AddWithValue("UserId", userId);
command.Parameters.AddWithValue("SalesPersonId", salesPersonId);
command.Parameters.AddWithValue("Price", txtPrice.Text);
command.Parameters.AddWithValue("DateSold", dateSold);
command.Parameters.AddWithValue("MonthlyPaymentDate", monthlyPaymentDate);
command.Parameters.AddWithValue("MonthlyPaymentAmount", txtPaymentAmount.Text);
//connection.Open();
int k = command.ExecuteNonQuery();
command.Parameters.Clear();
if (k != 0)
{
Response.Redirect("~/AdminPanel/CarSold.aspx");
}
else
{
lblAns.Text = "Record Not Inserted into the database";
lblAns.ForeColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
lblAns.Text = ex.Message;
}
Since Price column is float you need to write query with query parameter like this:
SqlCommand commandTwo = new SqlCommand("SELECT CarForSaleId, UserId, SalesPersonId FROM CarSold WHERE Price = #Price", connection);
commandTwo.Parameters.AddWithValue("#Price", txtPrice.Text);
The above mentioned command will give return you the carForSaleId, userId, salesPersonId which you will use in the insert command

upload a Excel file without header in Grid View (already defined column names) in asp .net C#, each time it show error when reaches at dt.Rows.Add()

here the code which i am using to import excel to grid view.. Each time getting error at dt.Rows.Add()
here the error "The string was not recognized as a valid DateTime. There is an unknown word starting at index 0.Couldn't store in SUPPLY DATE Column. Expected type is DateTime."
in .aspx page i don't defined any column with datetime
DataTable dtExl = conUpLoad.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string getExcelSheetName = dtExl.Rows[0]["Table_Name"].ToString();
OleDbCommand ExcelCommand = new OleDbCommand("Select * From [" + getExcelSheetName + "]", conUpLoad);
OleDbDataAdapter ExcelAdapter = new OleDbDataAdapter(ExcelCommand);
DataSet ExcelDataSet = new DataSet();
ExcelAdapter.Fill(ExcelDataSet);
//conUpLoad.Close();
// Clearing the grid ::::::::::::::::::::::
ViewState["dt"] = null;
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
// ::::::::::::::::::::::::::::::::::::::::
DataTable dt = ExcelDataSet.Tables[0];
int i = 0;
if (ExcelDataSet.Tables[0].Rows.Count > 0)
{
String DINumber = ExcelDataSet.Tables[0].Rows[0][0].ToString();
String PartNo = ExcelDataSet.Tables[0].Rows[0][1].ToString();
String DeliveryDt = Convert.ToDateTime(ExcelDataSet.Tables[0].Rows[0][3].ToString()).ToString("dd-MMM-yyyy");
String Location = ExcelDataSet.Tables[0].Rows[0][5].ToString();
String Qty = ExcelDataSet.Tables[0].Rows[0][7].ToString();
String PartyCode = ExcelDataSet.Tables[0].Rows[0][10].ToString();
dt.Rows.Add(DINumber, PartNo, DeliveryDt, Location, Qty, PartyCode);
ViewState["dt"] = dt;
GridView1.DataSource = ViewState["dt"] as DataTable;
GridView1.DataBind();
i++;
}
else
{
GridView1.DataSource = null;
GridView1.DataBind();
}

Gridview not populating by datatable

Below is the code where The four columns("Challan Number","Proposal Number","CTS Number" and "Amount") is obtained from Sql-Database, and the ("Land" and "Ward") values are obtained from respective methods. The values obtaines are correct but still the "ChallanGridview" is not getting populated.
The datarow "dr1" gets populated with the correct required values, but the "ChallanGridview" doesn't shows anything.
public void FillChallanGrid()
{
string query = string.Empty;
string cs = ConfigurationManager.ConnectionStrings["ConStrg"].ConnectionString;
query = CtrlChallenSearch1.GetChallanQuery();
using(SqlConnection con=new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter(query,con);
DataSet ds = new DataSet();
da.Fill(ds,"entry");
int x = ds.Tables["entry"].Rows.Count;
DataTable dt = new DataTable();
dt.Columns.Add("Challan Number");
dt.Columns.Add("Proposal Number");
dt.Columns.Add("CTS Number");
dt.Columns.Add("Amount");
dt.Columns.Add("Land");
dt.Columns.Add("Ward");
for(int i=0;i<x;i++)
{
DataRow dr = ds.Tables["entry"].Rows[i];
DataRow dr1 = dt.NewRow();
dr1["Challan Number"] = dr["ReceiptNo"].ToString();
dr1["Proposal Number"] = dr["ProposalNo"].ToString();
dr1["CTS Number"] = dr["CTSNo"].ToString();
dr1["Amount"] = dr["Amount"].ToString();
dr1["Land"] = GetLand(dr["ProposalNo"].ToString());
dr1["Ward"]=GetWard(dr["ProposalNo"].ToString());
dt.Rows.Add(dr1);
}
ChallanGridView.DataSource = dt;
ChallanGridView.DataBind();
}
}
private object GetLand(string ProposalNumber)
{
string retvalue = string.Empty;
if (ProposalNumber != "" || ProposalNumber != null || ProposalNumber != string.Empty)
{
string[] splittedvalue = ProposalNumber.Split('/');
retvalue = splittedvalue[1];
}
return retvalue;
}
private object GetWard(string ProposalNumber)
{
string retvalue = string.Empty;
string[] splittedvalue = new string[3];
splittedvalue = ProposalNumber.Split('/');
retvalue = splittedvalue[0];
return retvalue;
}
protected void Button1_Click(object sender, EventArgs e)
{
FillChallanGrid();
}
Its solved, I just deleted the present gridview and added another fresh one,
don't know how and why, but the error was gone.
btw thnks Asif.Ali!

C# Gridview Search

Expert my search function is not working. Not sure where i went wrong.
My code is
public partial class _Default : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=foc; Trusted_Connection=yes;");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
Button1_Click(Button1, null);
TextBox1_TextChanged(TextBox1, null);
}
}
protected void BindGrid()
{
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "SELECT MIN([sddoc]) AS[sddoc],[Soldtopt], [tradingname], [REP],MIN([DELTXT]) AS[Preseller Text], SUM(try_cast([Orderqty] as float)) AS[Orderqty],count(distinct Orderqty) as Qtycount , [DlvDate], SUM(try_cast(Netvalue as float)) as Netvalue, count(distinct SDDoc) as Salesdoc , count(distinct case when Netvalue = '0' then 1 else null end) as ZeroValue , count(distinct SDDoc) - count(distinct case when Netvalue = '0' then 1 else null end) As Result FROM [FOC].[dbo].[foc] where dlvdate = #dlvdate GROUP by Soldtopt,tradingname,REP,DlvDate HAVING SUM(try_cast(Netvalue as float)) = 0 and count(distinct SDDoc) = 1 and count(distinct case when Netvalue = '0' then 1 else null end) = 1";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#dlvdate", TextBox1.Text);
cmd.ExecuteNonQuery();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
conn.Close();
gvEmployeeDetails.DataSource = ds;
gvEmployeeDetails.DataBind();
}
protected void gvEmployeeDetails_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblEmpID = (Label)e.Row.FindControl("lblEmpID");
GridView gv_Child = (GridView)e.Row.FindControl("gv_Child");
string txtempid = lblEmpID.Text;
DataSet ds = new DataSet();
conn.Open();
string cmdstr = "Select * from [FOC].[dbo].[foc] where sddoc=#sddoc";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#sddoc", txtempid);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conn.Close();
gv_Child.DataSource = ds;
gv_Child.DataBind();
}
}
Hi problem is solved by binding the grid with button click.

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);

Resources