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!
Related
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();
}
I want to insert data into 12 different tables on a single click of a button. For this I am using single stored procedure. But my problem is when I am doing this and if there is any exception occurs my data is getting inserted partially i.e values is getting inserted in some tables and some remains empty and due to this problem occurs since all are related to one another. So wanted to know is there any way to perform Rollback so that if any exception occurs entire query is rolled back and data is not inserted in any of the table.
This is the code I am currently using for inserting values.
public int Sp_InsertUpdateDelete(string s, SqlParameter[] spa)
{
SqlConnection sc = new SqlConnection(cs);
sc.Open();
SqlCommand scm = new SqlCommand(s, sc);
scm.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter sql in spa)
{
scm.Parameters.Add(sql);
}
int k = scm.ExecuteNonQuery();
sc.Close();
return k;
}
protected void btnHostingSubmit_Click(object sender, EventArgs e)
{
string select = "select * from tbl_Hosting where Customer_Id='" + ddlCustomerName.SelectedValue + "'";
DataSet s = gs.select(select);
if (s.Tables[0].Rows.Count > 0)
{
Response.Write("<script>alert('Customer Already Exist');</script>");
}
else
{
if (ddlHosting.SelectedValue == "Yes")
{
SqlParameter[] spa = new SqlParameter[29];
spa[0] = new SqlParameter("#Customer_Id", Convert.ToInt16(ddlCustomerName.SelectedValue));
spa[1] = new SqlParameter("#Type", 2);
//Hosting
if (txtHostingSDate.Text == "" || txtHostingSDate.Text == null)
{
spa[2] = new SqlParameter("#Hosting_start_date", null);
}
else
{
spa[2] = new SqlParameter("#Hosting_start_date", Convert.ToDateTime(txtHostingSDate.Text));
}
if (txtHosingEDate.Text == "" || txtHosingEDate.Text == null)
{
spa[3] = new SqlParameter("#Hosting_end_date", null);
}
else
{
spa[3] = new SqlParameter("#Hosting_end_date", Convert.ToDateTime(txtHosingEDate.Text));
}
spa[4] = new SqlParameter("#Hosting_provider", ddlHostingPro.SelectedItem.ToString());
spa[5] = new SqlParameter("#Hosting_type", ddlHostingType.SelectedItem.ToString());
spa[6] = new SqlParameter("#Hosting_server", ddlHostingServer.SelectedItem.ToString());
spa[7] = new SqlParameter("#Hosting_total_id", Convert.ToInt16(txtHostingId.Text));
spa[8] = new SqlParameter("#Hosting_mail_tracking", ddlHostingMailTracking.SelectedItem.ToString());
spa[9] = new SqlParameter("#Hosting_mail_tracking_users", Convert.ToInt16(txtHostingMtUser.Text));
spa[10] = new SqlParameter("#Hosting_dns", ddlHostingDns.SelectedItem.ToString());
spa[11] = new SqlParameter("#Hosting_mail", ddlHostingMail.SelectedItem.ToString());
spa[12] = new SqlParameter("#Hosting_web", ddlHostingWeb.SelectedItem.ToString());
spa[13] = new SqlParameter("#Hosting_manage_dns", ddlHostingMngDns.SelectedItem.ToString());
if (ddlHostingDns.SelectedValue == "No" && (ddlHostingMail.SelectedValue == "Yes" || ddlHostingWeb.SelectedValue == "Yes"))
{
spa[14] = new SqlParameter("#Hosting_ns1", txtNS1.Text);
spa[15] = new SqlParameter("#Hosting_ns2", txtNS2.Text);
}
else
{
spa[14] = new SqlParameter("#Hosting_ns1", ddlHostingNS1.SelectedItem.ToString());
spa[15] = new SqlParameter("#Hosting_ns2", ddlHostingNS2.SelectedItem.ToString());
}
spa[16] = new SqlParameter("#Hosting_rec_ip", txtHostingARecordIp.Text);
spa[17] = new SqlParameter("#Hosting_mx_rec1", txtMXRecord1.Text);
spa[18] = new SqlParameter("#Hosting_mx_rec2", txtMXRecord2.Text);
spa[19] = new SqlParameter("#Hosting_mx_ip1", txtHostingMxIp1.Text);
spa[20] = new SqlParameter("#Hosting_space", ddlHostingSpace.SelectedItem.ToString());
spa[21] = new SqlParameter("#Hosting_mx_ip2", txtHostingMxIp2.Text);
spa[22] = new SqlParameter("#Hosting_data_transfer", ddlhostingDataTrans.SelectedItem.ToString());
spa[23] = new SqlParameter("#Hosting_manage_dns_amt", txtHostingMangDnsAmt0.Text);
spa[24] = new SqlParameter("#Hosting_amt", txtHostingAmt0.Text);
spa[25] = new SqlParameter("#Hosting_c_ns1", txtHostingNS1.Text);
spa[26] = new SqlParameter("#Hosting_c_ns2", txtHostingNS2.Text);
spa[27] = new SqlParameter("#Hosting_c_ns3", txtHostingNS3.Text);
spa[28] = new SqlParameter("#Hosting_c_ns4", txtHostingNS4.Text);
int k = gs.Sp_InsertUpdateDelete("Sp_Hosting", spa);
if (k > 0)
{
Response.Write("<script>alert('Hosting Added Success');</script>");
}
Clear();
}
using(SqlConnection conn = new SqlConnection())
{
try
{
conn.Open();
SqlTransaction tran = conn.BeginTransaction("Transaction1");
Cmd = new SqlCommand(sQuery, Conn);
Cmd.Transaction = tran;
//Your Code
tran.Commit(); //both are successful
}
catch(Exception ex)
{
//if error occurred, reverse all actions. By this, your data consistent and correct
tran.Rollback();
}
}
https://msdn.microsoft.com/en-us/library/a90c30fy.aspx
You need to modify your Stored procedure and use Transactions for this feature.
Something like this:
DECLARE #TranName VARCHAR(20);
SELECT #TranName = 'MyTransaction';
BEGIN TRANSACTION #TranName;
USE AdventureWorks2012;
DELETE FROM AdventureWorks2012.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION #TranName;
GO
MSDN Reference
When I execute this program the Excel part generates and string array: cellValue just fine.
When it inserts into the SQL MDF Database: MDFExcel every cell displays: "System.__ComObject".
How do you display the string value instead of the "System.__ComObject"?
protected void Button1_Click(Object sender, EventArgs e)
{
DataSet ds = new DataSet();
//From Excel
Microsoft.Office.Interop.Excel.Application exlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook exlWb = exlApp.Workbooks.Open(#"C:\Users\Optiplex760\Documents\a Excel\ExcelToMDF.xls");
Microsoft.Office.Interop.Excel.Worksheet exlWs= exlWb.Sheets["Sheet1"];
Microsoft.Office.Interop.Excel.Range usedRange = exlWs.UsedRange;
int col = Convert.ToInt32(usedRange.Columns.Count);
int row = Convert.ToInt32(usedRange.Rows.Count);
exlApp.Visible = true;
string[,] cellValue = new string[row + 1, col + 1];
for (int j = 1; j <= row-1; j++)
{
for (int k = 1; k <= col-1; k++)
{
cellValue[j, k] = exlWs.Cells[j+1,k+1].ToString();
}
}
exlWb.Close();
exlWs = null;
exlWb = null;
exlApp.Quit();
exlApp = null;
//To MSSQL
String connStr, cmdStr;
connStr = ConfigurationManager.ConnectionStrings["MDFExceldb"].ConnectionString;
for (int h = 1; h<row; h++)
{
cmdStr = "INSERT INTO [Table1] (col1,col2,col3) VALUES (#col1,#col2,#col3);";
try
{
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#col1", cellValue[1, h]);
cmd.Parameters.AddWithValue("#col2", cellValue[2, h]);
cmd.Parameters.AddWithValue("#col3", cellValue[3, h]);
cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = ex.ToString();
}
}
}
Worksheet.Cells returns a Range and not a single value - and a Range (an RCW object) does not implemented a sensible ToString; thus it defaults to the "System.__ComObject" value shown.
Use the Text property of the Range, eg.
cellValue[j, k] = Convert.ToString(exlWs.Cells[j+1,k+1].Text);
While this should fix the immediate problem, it is also an inefficient process. See this response (using the Value/Value2 property) for how to access the Range values as a 2-dimensional array and reduce excessive range-slicing.
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
I have placed grid view in update panel with first row as empty and it is not bound with any data base. Rather I have bound grid view with data table. Whenever I click on 'Add New Row' button, a new row is created in grid view there by retaining the data field in old rows but my problem is whenever I click on save button, at that time data of first row is not retried but I can get the data that is filled in second row and onwards. I have saved my data table in session and again retrieving it after each post back.
Here is the code of my .aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using AppResumeMaster;
using System.Collections;
using AppQualificationDetail;
public partial class Applicant_ApplicationForm : System.Web.UI.Page
{
int Rows = 1;
object MaxAppId = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
setInitialRow();
}
}
protected void saveBtn_Click(object sender, EventArgs e)
{
try
{
using (DataOperation oDo = new DataOperation())
{
MaxAppId= oDo.ExecuteScaler("select max(AppId) from tblAppResumeMaster");
if (MaxAppId == System.DBNull.Value)
MaxAppId = 0;
}
using (AppResumeMasterClass objAppResumeMasterClass = new AppResumeMasterClass())
{
objAppResumeMasterClass.AppId = Convert.ToInt32(MaxAppId)+1;
objAppResumeMasterClass.AppFirstName = firstnameBox.Text;
objAppResumeMasterClass.AppLastName = lastnameBox.Text;
objAppResumeMasterClass.AppAddress1 = CurAddBox.Text;
objAppResumeMasterClass.AppCity1 = CurAddBox.Text;
objAppResumeMasterClass.AppState1 = CurStateBox.Text;
objAppResumeMasterClass.AppCountry1 = CurCountrybox.Text;
objAppResumeMasterClass.AppAddress2 = PerAddBox.Text;
objAppResumeMasterClass.AppCity2 = PerCityBox.Text;
objAppResumeMasterClass.AppState2 = PerStateBox.Text;
objAppResumeMasterClass.AppCountry2 = PerCountrybox.Text;
objAppResumeMasterClass.AppEmail1 = emailBox.Text;
objAppResumeMasterClass.AppEmail2 = AltEmailBox.Text;
objAppResumeMasterClass.AppMobileNo = mobileNoBox.Text;
objAppResumeMasterClass.AppContactNo = phoneNoBox.Text;
objAppResumeMasterClass.AppDOB = Convert.ToDateTime(birthDateBox.Text);
objAppResumeMasterClass.AppKeySkill = skillsBox.Text;
objAppResumeMasterClass.AppGoal = goalBox.Text;
objAppResumeMasterClass.AppWeakness = weaknessBox.Text;
objAppResumeMasterClass.AppStrengths = strengthsBox.Text;
objAppResumeMasterClass.setVal(1);
}
DataTable Table = (DataTable)Session["CurTable"];
int cnt = Table.Rows.Count;
using(AppQualificationDetailClass objAppQualificationDetail = new AppQualificationDetailClass())
{
for (int RowCnt = 0; RowCnt < Table.Rows.Count; RowCnt++)
{
objAppQualificationDetail.AppId = Convert.ToInt32(MaxAppId) + 1;
objAppQualificationDetail.QualiId = Convert.ToInt32(Table.Rows[RowCnt][1]);
objAppQualificationDetail.Year = Convert.ToInt32(Table.Rows[RowCnt][3]);
objAppQualificationDetail.Percentage = (float)Table.Rows[RowCnt][2];
objAppQualificationDetail.InstiName = Table.Rows[RowCnt][4].ToString();
objAppQualificationDetail.setVal(1);
}
}
ExistMsgLbl.Text = Table.Rows[0][2].ToString();
}
catch (Exception ex)
{
throw ex;
}
}
protected void addRowBtn_Click(object sender, EventArgs e)
{
AddNewRow();
}
protected void InstituteLbl_PreRender(object sender, EventArgs e)
{
//Session.Add("Table", Table1);
}
public void setInitialRow()
{
DataTable Table = new DataTable();
DataRow dr = null;
Table.Columns.Add(new DataColumn("Qualification",typeof(string)));
Table.Columns.Add(new DataColumn("QualiId",typeof(string)));
Table.Columns.Add(new DataColumn("Percentage",typeof(string)));
Table.Columns.Add(new DataColumn("Passing Year",typeof(string)));
Table.Columns.Add(new DataColumn("Institute Name",typeof(string)));
dr = Table.NewRow();
dr["Percentage"] = string.Empty;
dr["Passing Year"] = string.Empty;
dr["Institute Name"]=string.Empty;
Table.Rows.Add(dr);
Session.Add("CurTable", Table);
GridView1.DataSource = Table;
GridView1.DataBind();
ArrayList Array = new ArrayList();
DataSet ds = new DataSet();
DropDownList DDL = (DropDownList)GridView1.Rows[0].Cells[0].FindControl("QualificationList");
FillDropDownList(DDL);
}
public void AddNewRow()
{
DataSet ds=new DataSet();
int RowIndex = 0;
if (Session["CurTable"] != null)
{
DataTable CurTable = (DataTable)Session["CurTable"];
DataRow CurRow = null;
if (CurTable.Rows.Count > 0)
{
CurRow = CurTable.NewRow();
CurTable.Rows.Add(CurRow);
Session.Add("CurTable", CurTable);
for (int count = 0; count < CurTable.Rows.Count - 1; count++)
{
DropDownList DDL = (DropDownList)GridView1.Rows[count].Cells[0].FindControl("QualificationList");
TextBox PercentageBox = (TextBox)GridView1.Rows[count].Cells[1].FindControl("percentageBox");
TextBox yearBox = (TextBox)GridView1.Rows[count].Cells[1].FindControl("yearBox");
TextBox InstituteNameBox = (TextBox)GridView1.Rows[count].Cells[1].FindControl("InstituteNameBox");
CurTable.Rows[count]["Percentage"] = PercentageBox.Text;
CurTable.Rows[count]["Passing Year"]=yearBox.Text;
CurTable.Rows[count]["Institute Name"]=InstituteNameBox.Text;
CurTable.Rows[count]["Qualification"]=DDL.SelectedItem.Text;
CurTable.Rows[count]["QualiId"] = DDL.SelectedValue;
}
GridView1.DataSource = CurTable;
GridView1.DataBind();
}
}
setPreviousData();
}
public void setPreviousData()
{
int RowIndex = 0;
if (Session["CurTable"] != null)
{
DataTable RestoreTable = (DataTable)Session["CurTable"];
if (RestoreTable.Rows.Count > 0)
{
for (int row = 0; row < RestoreTable.Rows.Count; row++)
{
DropDownList DPList = (DropDownList)GridView1.Rows[row].Cells[0].FindControl("QualificationList");
TextBox PercentageBox = (TextBox)GridView1.Rows[row].Cells[1].FindControl("percentageBox");
TextBox YearBox = (TextBox)GridView1.Rows[row].Cells[2].FindControl("yearBox");
TextBox InstituteName = (TextBox)GridView1.Rows[row].Cells[3].FindControl("InstituteNamebox");
FillDropDownList(DPList);
if (row < RestoreTable.Rows.Count - 1)
{
PercentageBox.Text = RestoreTable.Rows[row]["Percentage"].ToString();
YearBox.Text = RestoreTable.Rows[row]["Passing Year"].ToString();
InstituteName.Text = RestoreTable.Rows[row]["Institute Name"].ToString();
DPList.ClearSelection();
DPList.Items.FindByText(RestoreTable.Rows[row]["Qualification"].ToString()).Selected = true;
}
RowIndex++;
}
}
}
}
private ArrayList FillArrayList()
{
ArrayList ArrayList = new ArrayList();
DataSet ds = new DataSet();
using(DataOperation oDo = new DataOperation())
{
ds =oDo.DropDownList("select * from tblQualificationMaster");
for(int count=0;count<ds.Tables[0].Rows.Count;count++)
{
ArrayList.Add(new ListItem(ds.Tables[0].Rows[count][1].ToString(), ds.Tables[0].Rows[count][0].ToString()));
}
}
return ArrayList;
}
private void FillDropDownList(DropDownList DDL)
{
ArrayList ArrayList = FillArrayList();
foreach (ListItem item in ArrayList)
{
DDL.Items.Add(item);
}
}
}
Use ViewState instead of Session.