Different dropdowns with same source giving same value. How to handle? - asp.net

I've bound three drop down lists with same oledb data adapter. this oledbdataadapter fills three different datatables which I use eventually to fill up three dropdowns. But when I access three dropdown values in submit button, all three dropdowns give same selected item even when I've selected three different options in dropdowns. Can Anybody help?
here's my code:-
//oda - oledbdataadapter
oda.SelectCommand = cmdExcel;
oda.Fill(dt_Temp);
DataTable dt_costcode = new DataTable();
oda.Fill(dt_costcode);
DataTable dt_desc = new DataTable();
oda.Fill(dt_desc);
DataTable dt_unit = new DataTable();
oda.Fill(dt_unit);
connExcel.Close();
ViewState["TempImport"] = dt_Temp;
List<CostColumns> list_costCode = Columns(dt_costcode);
Bind_ddlCostCode(list_costCode);
List<CostColumns> list_desc = Columns(dt_desc);
Bind_ddlDescription(list_desc);
List<CostColumns> list_unit = Columns(dt_unit);
Bind_ddlUnitofMeasure(list_unit);
here code for binding Dropdowns:-
public void Bind_ddlCostCode(List<CostColumns> list_costCode)
{
foreach (CostColumns costcol in list_costCode.ToList())
{
if (costcol.ColumnType == "System.String")
{
ddlCostCodeNumber.Items.Add(new ListItem(costcol.Columns, costcol.ColumnType));
}
}
ddlCostCodeNumber.DataBind();
ddlCostCodeNumber.Items.Insert(0, new ListItem("--Select CostCode--", "0"));
}
public void Bind_ddlDescription(List<CostColumns> list_desc)
{
foreach (CostColumns costcol in list_desc.ToList())
{
if (costcol.ColumnType == "System.String")
{
ddlDescription.Items.Add(new ListItem(costcol.Columns, costcol.ColumnType));
}
}
ddlDescription.DataBind();
ddlDescription.Items.Insert(0, new ListItem("--Select Desc.--", "0"));
}
//(Same code for Bind_ddlUnitofMeasure(list_unit))
And here's where It all goes wrong:-
protected void Btn_ImportRecords_Click(object sender, EventArgs e)
{
DataTable dt_Temp= (DataTable)ViewState["TempImport"];
DataTable dt_Import = new DataTable();
Int32 i = costCodeNo();
string ccn = ddlCostCodeNumber.SelectedItem.Text;//gives same selected option(CostCodeNumber)
string desc = ddlDescription.SelectedItem.Text;//gives same selected option
string unit = ddlUnitofMeasure.SelectedItem.Text;//gives same selected option
dt_Import.Columns.Add(new DataColumn("CostCodeNo", typeof(Int32)));
dt_Import.Columns.Add(new DataColumn(ddlCostCodeNumber.SelectedItem.Text, typeof(string)));
dt_Import.Columns.Add(new DataColumn(ddlDescription.SelectedItem.Text, typeof(string)));
//throws exception that dt_Import already has same column name
}

Related

Set focus on the repeated row data while typing duplicate value

I have a gridview in asp.net, in which I am inserting datas. When I insert repeated value then it will show item repeated. Now I need to show after the item repeated alert message the cursor will focus on the row value contain the item which is repeated. If my data table already contain code C1, then I again type c1 for insert then the cursor will focus on the row which contain c1 in gridview. Here is my code
protected void Button15_Click(object sender, EventArgs e)
{
Control control = null;
if (GridView1.FooterRow != null)
{
control = GridView1.FooterRow;
}
else
{
control = GridView1.Controls[0].Controls[0];
}
string Code = (control.FindControl("txtcode") as TextBox).Text;
string txtno= (control.FindControl("txtno") as TextBox).Text;
using (SqlConnection con = new SqlConnection("Data Source=XXXXXX;Initial Catalog=XXXXXX;User ID=XXXX;Password=XXXXXX"))
{
using (SqlCommand cmd = new SqlCommand())
{
DataTable dt = new DataTable();
SqlDataAdapter da1;
da1 = new SqlDataAdapter("select code from tbltmp where code='" + Code + "' ", con);
da1.Fill(dt);
if (dt.Rows.Count > 0)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"alertMessage",
"alert('Item Repeated');", true);
(control.FindControl("txtcode") as TextBox).Focus();
}
else
{
(control.FindControl("txtno") as TextBox).Focus();
}
}
}
}
set focus on the textbox as textbox1.focus in button event of repeated row checking

how to get total of all column if GridView Paging is set as “True”?

this code display total of column in each page of grid view footer I want to display total of all columns in all pages footer
if (e.Row.RowType == DataControlRowType.DataRow)
{
string deb = ((Label)e.Row.FindControl("debit")).Text;
string cred = ((Label)e.Row.FindControl("credit")).Text;
decimal totalvalue = Convert.ToDecimal(deb) - Convert.ToDecimal(cred);
amount += totalvalue;
Label lbl = (Label)e.Row.FindControl("lblTotal");
lbl.Text = amount.ToString();
Label lblDebAmount = (Label)e.Row.FindControl("debit");
Label lblCredamount = (Label)e.Row.FindControl("credit");
float debtotal = (float)Decimal.Parse(lblDebAmount.Text);
float credtotal = (float)Decimal.Parse(lblCredamount.Text);
totalPriced += debtotal;
totalPricec += credtotal;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label totallblCAmount = (Label)e.Row.FindControl("totallblDebAmount");
Label totallblCredAmount = (Label)e.Row.FindControl("totallblCredAmount");
totallblCAmount.Text = totalPriced.ToString("###,###.000");
totallblCredAmount.Text = totalPricec.ToString("###,###.000");
}
}
Why do it when the row is data bound? Why not do it when you originally bind the data?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
DataTable dt = Database.GetData();
GridView1.DataSource = dt;
GridView1.DataBind();
//calculate here by manually adding up the debit/credit column from dt
//or do a separate database call that calculates the sum, ex: select sum(debits), sum(credits) from general_ledger
}
}
It makes sense to let the database do the math calculation for you. You wouldn't need to write your own custom calculation code. Just let the database's sum function handle it.
Here's a little more detail.
//Executes a SqlCommand and returns a DataTable
public class GetDataTable(SqlCommand command)
{
var dt = new DataTable();
using (var connection = new SqlConnection("connectionstring"))
{
command.Connection = connection;
connection.Open();
dt.Load(command.ExecuteReader());
}
return dt;
}
//Executes a SqlCommand and returns a scalar of type T
public static T GetScalar<T>(SqlCommand command)
{
using (var connection = new SqlConnection ("connectionstring"))
{
command.Connection = connection;
connection.Open();
var result = command.ExecuteScalar();
if (result is T)
{
return (T)result;
}
else
{
return (T)Convert.ChangeType(result, typeof(T));
}
}
}
//Load the data into the GridView, then get the credit amount and put the value in a label.
//You'll need to adjust the queries to match your schema
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
var tableCommand = new SqlCommand("select columns from table");
GridView1.DataSource = GetDataTable(tableCommand);
GridView1.DataBind();
var creditCommand = new SqlCommand("select sum(stat_amount) from tablename where stat_flag='c'");
var credits = GetScalar<decimal>(creditCommand);
Label1.Text = credits;
}
}

how to get gridview all rows data when using paging

I have a gridview with paging (page size 10), which contains Course details. when i am saving gridview data into database it save only 10 record (according to page).
is there any to get all gridview all rows.
e.g. if my gridview contains 25 rows with paging and when i save data into database then all 25 rows data insert into database?
please help...
Here is my code
DataTable dt = new DataTable();
dt.Columns.Add("row_index");
dt.Columns.Add("edited_value");
IList<int?> SeqNos = new List<int?>();
foreach (GridViewRow gvr in gvViolationCodes.Rows)
{
TextBox tb = (TextBox)gvr.FindControl("txtSeqNo");
Label lblSysid = (Label)gvr.FindControl("lblSysID");
HiddenField hf = (HiddenField)gvr.FindControl("HiddenField1");
if (tb.Text != hf.Value)
{
DataRow dr = dt.NewRow();
SeqNos.Add(Convert.ToInt32(tb.Text));
dr["row_index"] = lblSysid.Text;
dr["edited_value"] = tb.Text;
dt.Rows.Add(dr);
}
}
You need to save the data in temporary storage in PageIndexChanging event of GrIdView. On final save send the datatable to Sql Server Procedure or loop through the datatable and save it in database. Follow the steps:
protected void grdView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
fnStoreGridData();
}
private void fnStoreGridData()
{
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
else{
TempDataTable.Columns.Add("exCourse", typeof(string)) ;
TempDataTable.Columns.Add("exUniversityCourse", typeof(string)) ;
}
foreach (GridViewRow row in gvExportCourse.Rows)
{
Label exCourse = (Label)row.FindControl("gvlblCourseName");
Label exUniversityCourse = (Label)row.FindControl("gvlblUniversityCourseName");
if (exCourse != null)
{
if (!string.IsNullOrEmpty(exCourse.Text))
{
TempDataTable.Rows.Add(exCourse.Text, exUniversityCourse.Text);
//TempDataTable is your datatable object. Make sure that datatable contains these columns
}
}
}
}
In Final Save:
protected void button_Click(object s, EventArg e)
{
fnStoreGridData(); //Here this will bind the data of current page
DataTable TempDataTable = new DataTable();
if(Session["Data"]!=null){
TempDataTable = Session["Data"] as DataTable;
}
//Now loop through datatable and store the values
foreach(DataRow in TempDataTable.Rows)
{
CourseInformation course = new CourseInformation();
course.AddCourseMaster(dr["exCourse"].ToString(), dr["exUniversityCourse"].ToString());
}
label1.Text = "Course saved successfully.";
}

Asp.net markup file

I have been given some c# code and have been asked to create a markup (.aspx) file that would go along with it.
I am not asking for help to write the code, but instead, how to go about it.
Here is the code:
public partial class search : Page
{
protected override void OnLoad(EventArgs e)
{
int defaultCategory;
try
{
defaultCategory = Int32.Parse(Request.QueryString["CategoryId"]);
}
catch (Exception ex)
{
defaultCategory = -1;
}
Results.DataSource = GetResults(defaultCategory);
Results.DataBind();
if (!Page.IsPostBack)
{
CategoryList.DataSource = GetCategories();
CategoryList.DataTextField = "Name";
CategoryList.DataValueField = "Id";
CategoryList.DataBind();
CategoryList.Items.Insert(0, new ListItem("All", "-1"));
CategoryList.SelectedIndex = CategoryList.Items.IndexOf(CategoryList.Items.FindByValue(defaultCategory.ToString()));
base.OnLoad(e);
}
}
private void Search_Click(object sender, EventArgs e)
{
Results.DataSource = GetResults(Convert.ToInt32(CategoryList.SelectedValue));
Results.DataBind();
}
private DataTable GetCategories()
{
if (Cache["AllCategories"] != null)
{
return (DataTable) Cache["AllCategories"];
}
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * From Categories");
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
Cache.Insert("AllCategories", dt, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
connection.Dispose();
return dt;
}
private DataTable GetResults(int categoryId)
{
SqlConnection connection = new SqlConnection("Data Source=DB;Initial Catalog=Store;User Id=User;Password=PW;");
string sql = string.Format("SELECT * FROM Products P INNER JOIN Categories C on P.CategoryId = C.Id WHERE C.Id = {0} OR {0} = -1", categoryId);
SqlCommand command = new SqlCommand(sql, connection);
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
connection.Dispose();
return dt;
}
}
EDIT
In the above code, what is the Results object and is the CategoryList just a listbox?
As Nilesh said this seems like a search page, You can possibly try creating the a Webform using Visual studio which is just drag and drop controls into canvas and that will create the mark up for the controls in the code window.
This code behind seems to be doing the following,
On page load at Get request (when its !Page.IsPostBack) page is going to get categories using GetCategories() and fill the drop down list "CategoryList" with all category names (default selected one being the defaultcategory ID from query string).
The search button takes the dropdown's selected value and calls the GetResults() to get data table to fill the grid view "Results". So you need 3 controls (Dropdown list, Button, Gridview) in the webform with these names..

How to pass a Session to a DataTable?

In my asp project I need to write all Items form the list box into database table using TVP. I have listbox, stored procedure (passing TVP - Table Valued Parameters). The main problem is that passing DataTable is NULL, but the Session isn't. I'll send you my code form aspx.cs file (only one block, if you'll nedd more, let me know).
protected void ASPxButton1_Click(object sender, EventArgs e)
{
//DataTable dts = Session["SelectedOptions"] as DataTable;
DataTable _dt;
//_dt = new DataTable("Items");
_dt = Session["SelectedOptions"] as DataTable;
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
}
SqlConnection con;
string conStr = ConfigurationManager.ConnectionStrings["TestConnectionString2"].ConnectionString;
con = new SqlConnection(conStr);
con.Open();
using (con)
{
SqlCommand sqlCmd = new SqlCommand("TestTVP", con);
sqlCmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = sqlCmd.Parameters.AddWithValue("#testtvp", _dt);
tvpParam.SqlDbType = SqlDbType.Structured;
sqlCmd.ExecuteNonQuery();
}
con.Close();
}
EDIT
Debugging Screenshot
You are not adding the new rows to the DataTable. You need something like this:
foreach (ListEditItem item in lbSelectedOptions.Items)
{
DataRow dr = _dt.NewRow();
dr["Id"] = item.Value;
dr["Name"] = item.Text;
_dt.Rows.Add(dr);
}
A secondary concern is where are you initialising Session["SelectedOptions"]? It appears that every time ASPxButton1 is clicked the code will try and add Id and Name columns to it, even if it already contains those two columns. It would seem more logical to do something like:
_dt = Session["SelectedOptions"] as DataTable;
if (_dt == null)
{
_dt = new DataTable("Items");
_dt.Columns.Add("Id", typeof(int));
_dt.Columns.Add("Name", typeof(string));
Session.Add("SelectedOptions", _dt);
}

Resources