HOW TO HANDLE ERROR SOAPEXCEPTION WAS UNHANDLED IN C# - c#

I am trying to consume my webservice to my windows application. My webService
return datatable. Error occurs in my windows application.
here's my code:
this is my code in Web Service:
[WebMethod]
public DataTable searchCom(string compCode)
{
SqlConnection conn = new SqlConnection("Data Source=LOCALPC\\SQLEXPRESS1; Initial Catalog=Company;Integrated Security=True;");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("selectPress", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#item", SqlDbType.VarChar).Value = compCode;
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
This is my code in Windows Application Form:
private void button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = service.searchCom(textBox1.Text);
if(dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
textBox2.Text = row["CompanyName"].ToString();
textBox3.Text = row["balance"].ToString();
textBox4.Text = row["maintBalance"].ToString();
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
button1.Visible = false;
Back.Visible = true;
}
}
}

You should handle exception at web service level.
[WebMethod]
public DataTable searchCom(string compCode)
{
try
{
SqlConnection conn = new SqlConnection("Data Source=LOCALPC\\SQLEXPRESS1; Initial Catalog=Company;Integrated Security=True;");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("selectPress", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#item", SqlDbType.VarChar).Value = compCode;
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw new SoapException("Exception :",
SoapException.ServerFaultCode, "SoapException", ex);
}
}
Then catch the exception at consumer end
private void button2_Click(object sender, EventArgs e)
{
try
{
DataTable dt = new DataTable();
dt = service.searchCom(textBox1.Text);
if(dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
textBox2.Text = row["CompanyName"].ToString();
textBox3.Text = row["balance"].ToString();
textBox4.Text = row["maintBalance"].ToString();
textBox2.ReadOnly = true;
textBox3.ReadOnly = true;
textBox4.ReadOnly = true;
button1.Visible = false;
Back.Visible = true;
}
}
}
catch (SoapException ex)
{
if(ex.Actor == "SoapException")
//Do something
}
}

Have you set up the WebService to run as NTLM?
WebServices, by default, run as Anonymous in IIS. But you've got your SQL Connection using Integrated security (aka, the currently logged in user). Have you set your web service to run using NTLM or something? Because unless you go out of your way during your service setup and connection, you're going to get an exception because it can't connect into the SQL database as the default IIS user.

i try changing my web-service DataTable to DataSet and it works perfectly.
just answering my own problem :P
[WebMethod]
public DataSet searchCom(string compCode)
{
SqlConnection conn = new SqlConnection("Data Source=LOCALPC\\SQLEXPRESS1; Initial Catalog=Company;Integrated Security=True;");
conn.Open();
DataSet dt = new DataSet();
SqlCommand cmd = new SqlCommand("selectPress", conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.Add("#item", SqlDbType.VarChar).Value = compCode;
cmd.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}

Related

Asp.net the gridView does not show the row headers

I have this problem,
when the table is empty, the GridView does not show the row headers
i use .net framework 4 and internet Explorer,Can you help me?
this is the code:
this is code
private void loadTCOR27()
{
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
try
{
string sql = null;
gridViewTCOR27.Visible = true;
table1.Visible = false;
string connectionString = SestanteWeb.Global.rCRVigServer.leggiStringaConnessioneSicurezzaSqlClient();
sql = "select * FROM [PUMA2_FINANZIARIAFAMILIARE].[dbo].[TCOR27]";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand(sql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
command.Dispose();
connection.Close();
// gridView1.DataSource = ds.Tables[0];
gridViewTCOR27.DataSource = ds.Tables[0];
gridViewTCOR27.DataBind();
}
catch (Exception ex)
{
}
finally
{
adapter.Dispose();
}
}
Set the property ShowHeaderWhenEmpty to true in your Gridview declaration. May be it will help you.
Here is the reference to this property.
Ref

fill grid view in c#

I am new in using visual studio and ADO.NET. I want to display result from sqlserver database in data gridview.
This is my code but it does not fill data to gridview.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand Cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(Cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
SqlDataReader reader = Cmd.ExecuteReader();
dt.Load(reader);
dataGridView1.DataSource = dt;
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
Why are you binding to grid two times?
If your application is ASP.NET Webforms and you are trying to bind the GridView(ID for the GridView is "dataGridView1"), then make your binding to single time and to bind data for GridView you need to use dataGridView1.DataBind(); after dataGridView1.DataSource = dt;
If your application is WindowsForms application then modify your code like below
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
string connectionString = "Define your connection string here";
using(SqlConnection con = new SqlConnection(connectionString ))
{
SqlCommand cmd = new SqlCommand("sp_Expert_person", con);
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#takhasos", SqlDbType.VarChar).Value = comboBox1.SelectedText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
this.dataGridView1.Visible = true;
dataGridView1.DataSource = dt;
}
}

GridView does not bind with datasource

What is the problem with the following code? The GridView GridView1 does not show up on page at all.
public void display_range_mark()
{
int from = int.Parse(ddl_from_mark.SelectedValue.ToString());
int to = int.Parse(ddl_to_mark.SelectedIndex.ToString());
DataTable dt=Data.DoSomthing(string.Format("select ts.Name,ts.FamilyName,ts.Id_student,td.Name,tn.NomreAdad from tblStudent ts,tblDars td,tblNomre tn where tn.NomreAdad>='{0}' AND tn.NomreAdad<='{1}' AND ts.Id=tn.Id_student AND td.Id=tn.Id_dars",from,to));
//DataTable data = Data.DoSomthing(string.Format("select t.Name,t.Id from tblStd t where t.DateSabt='{0}'", p.GetYear(DateTime.Now)));
GridView1.DataSource = dt;
GridView1.HeaderRow.Cells[0].Text = "نام";
GridView1.HeaderRow.Cells[1].Text = "نام خانوادگی";
GridView1.HeaderRow.Cells[2].Text = "شماره دانش آموزی";
GridView1.HeaderRow.Cells[3].Text = "درس";
GridView1.HeaderRow.Cells[4].Text = "نمره";
GridView1.DataBind();
}
I am getting this error:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
The error occurs at this line:
GridView1.HeaderRow.Cells[0].Text = "نام";
By the way, the code for Data.DoSomthing is as folllows (It is located within class Database):
SqlConnection sc = new SqlConnection(#"Data Source=.;Initial Catalog=School;Integrated Security=True");
public DataTable DoSomthing(string text)
{
sc.Open();
DataTable data = new DataTable();
try
{
SqlCommand command = new SqlCommand();
command.Connection = sc;
command.CommandType = CommandType.Text;
command.CommandText = text;
SqlDataAdapter sd = new SqlDataAdapter(command);
sd.Fill(data);
if (data.Rows.Count == 0)
data = null;
}
catch (Exception ex)
{
sc.Close();
return null;
}
finally
{
if (sc.State != ConnectionState.Closed)
{
sc.Close();
}
}
return data;
}
Where is the connection object to connect to the database and fetch values ?
The way to do this:
string query="select ts.Name,ts.FamilyName,ts.Id_student,td.Name,tn.NomreAdad from tblStudent ts,tblDars td,tblNomre tn where tn.NomreAdad>=#from AND tn.NomreAdad<=#to AND ts.Id=tn.Id_student AND td.Id=tn.Id_dars";
//Create Sqlconnection object
using(SqlConnection con = new SqlConnection(connectionstring))
{
//open the connection
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(query, con);
//To avoid sql injection using parameters
sda.Paramaters.AddWithValue("#from",from);
sda.Paramaters.AddWithValue("#to",to);
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}

How to populate a DataGridView by selecting any table from combo box

I have used the following code for displaying names of my SQL db tables in a combo box.
Now I want that when I click on any of these table names from the combo box, my DGV populates with that table's contents.
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "TABLE_NAME";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Then I used the following code for populating my DGV but it's not working; please help.
private void PopulateGridView()
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedText;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
PopulateGridView(comboBox1.SelectedValue.ToString());
}
}
just try this:
update your code in the Form Load with below:
private void Form1_Load(object sender, EventArgs e)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select table_name from information_schema.tables";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
comboBox1.DataSource = dtRecord;
comboBox1.DisplayMember = "table_name";
comboBox1.ValueMember = "table_name";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
so basically you have added one extra line comboBox1.ValueMember = "table_name";
and make your PopulateGridView method like this:
private void PopulateGridView(string tblName)
{
String strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strConnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + tblName;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
it has to work.
Also, I see, you are creating SqlConnection object everywhere, including SqlCommand and SqlDataAdapter.
try to wrap them up in static methods i.e.
- public static SqlConnection OpenConnection()
- public static DataTable ExecuteSelectQuery(string Query)
- public static bool ExecuteModifyQuery(string Query)
try to write as less amount of code as you can.
Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue != null)
{
string strConnection = "Data Source=HP\\SQLEXPRESS;database=MK;Integrated Security=true";
SqlConnection con = new SqlConnection(strconnection);
try
{
con.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "select * from " + comboBox1.SelectedValue;
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);
DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = dtRecord;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

Populating a combolist automatically with data from SQL Server database

Can anyone help please, I am trying to populate the data automatically to my combobox without having to push any button, but by the dropdown control.....
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.AllowDrop == false)
{
SqlConnection conn = new SqlConnection("Data Source=localhost; database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Problem FROM PROBLEMT", conn);
DataTable dt = new DataTable();
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand("SELECT Problem FROM PROBLEMT", conn);
ad.Fill(ds, "Problem");
dataGridView1.DataSource = dt;
//Biding the data with the control
BindingSource bs = new BindingSource();
bs.DataSource = ds;
bs.DataMember = "Problem";
DataGridView dvg = new DataGridView();
this.Controls.Add(dvg);
dvg.DataSource = bs;
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox1.Items.Add(dt.Rows[i]["Problem"]);
}
}
else
{
}
}
you are missing a } and I hardly believe that SelectedIndexChanged is the best place to populate a combobox. Since obviously you are learning, try to put your code on a button, once it is working fine from the click of the button, you can look for a better place to it, like the form load for example.
also what exactly is the problem? does it give an error?
first create method for fetching data and load in combobox like this
protected void LoadCombo()
{
SqlConnection conn = new SqlConnection("Data Source=localhost;database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30");
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Problem FROM PROBLEMT", conn);
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = new SqlCommand("SELECT Problem FROM PROBLEMT", conn);
ad.Fill(ds, "Problem");
dataGridView1.DataSource = ds;
dataGridView1.DataBind();
for (int X = 0; X <= ds.Tables[0].Rows.Count - 1; X++)
{
comboBox1.Items.Add(ds.Tables[0].Rows[X]["Problem"].ToString());
}
}
now on page_load call this method
protected void Page_Load()
{
if(ispostback)
{
}
else
{
LoadCombo();
}
}
Answer to the question on how to populate a combobox automatically:
private void Form3_Load(object sender, EventArgs e)
{
using (SqlConnection sc = new SqlConnection())
{
sc.ConnectionString= "database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30";
sc.Open();
using (SqlDataAdapter sda = new SqlDataAdapter())
{
DataTable data = new DataTable();
sda.SelectCommand = new SqlCommand("SELECT ID, TypeProblem FROM eL_Section", sc);
sda.Fill(data);
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "ID";
comboBox1.DataSource = data;
comboBox2.ValueMember = "TypeProblem";
comboBox2.DisplayMember = "TypeProblem";
comboBox2.DataSource = data;
}
}
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString = "database=KnowledgeEssentials;Trusted_Connection=yes;connection timeout=30";
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter())
{
DataTable dat = new DataTable();
da.SelectCommand = new SqlCommand("SELECT UserName FROM UserT", cn);
da.Fill(dat);
comboBox3.ValueMember = "UserName";
comboBox3.DisplayMember = "UserName";
comboBox3.DataSource = dat;
}
}
// TODO: This line of code loads data into the 'knowledgeEssentialsDataSet.ProblemT' table. You can move, or remove it, as needed.
this.problemTTableAdapter.Fill(this.knowledgeEssentialsDataSet.ProblemT);
}

Categories