i am using DataAdapter to fill my DataTable with query as Stored Procedure.
But there is an exception ArgumentNullExceptioncoming when i try to Fill DataTable. I tested the query and its working fine.
Here's my code:
if (!IsPostBack)
{
Session["NewsId"] = Convert.ToInt32(Request.QueryString["news"]);
if (Session["NewsId"] != null && Convert.ToInt32(Session["NewsId"]) != 0)
{
id = Convert.ToInt32(Session["NewsId"]);
}
}
da = new SqlDataAdapter("NewsGallerySelect", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add("#NewsID", SqlDbType.Int).Value = id;
da.Fill(dt);
if (dt.Rows.Count > 0)
{
rptrNews.DataSource = dt;
rptrNews.DataBind();
foreach (DataRow row in dt.Rows)
{
lblShrtDesc.Text = row["ShortDesc"].ToString();
lblShrtDesc2.Text = row["ShortDesc"].ToString();
lblDesc.Text = row["NewsDesc"].ToString();
lblDesc2.Text = row["NewsDesc"].ToString();
lblDate.Text = row["NewsDate"].ToString();
}
}
Related
My logic is:
"if selected date is a match with the database date from Holiday table, return message as "OK"
I have already formatted date in the code shown below. When I do test with hardcoded database date, the code works fine.
How to get database date from my Holiday table?
PS: Holiday table includes different dates so system needs to loop and search every row in Holiday table.
Code:
[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
//hardcoded is ok
string dbDateString = "2019-02-20";
DateTime date1 = DateTime.ParseExact(dbDateString.Split(' ')[0], "yyyy/MM/dd", null);
string dateDB = date1.ToString("yyyy/MM/dd");
if (dateDB == selectedDate)
{
return "OK";
}
else
{
return "NG";
}
}
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday where Date='" + selectedDate + "'", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt == null || dt.Rows.Count() == 0)
return "NG";
else
return "OK";
You said you have multi rows so you just can return "OK" or "NG" after loop all row (or break when have error):
[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt != null && dt.Rows.Count > 0)
{
string formatDate = "yyyy/MM/dd";
foreach (DataRow dr in dt.Rows)
{
string dateString = dr["yourColumnName"].ToString();
if (string.IsNullOrEmpty(dateString))
{
continue; // Or set error or something
}
dateString = DateTime.ParseExact(dateString.Split(' ')[0], formatDate, null).ToString(formatDate);
if (dateString.Equals(compareDate))
{
// Do something
}
else
{
// Set error message or something
}
}
// Check after loop and return "OK" or "NG"
}
}
I'm trying to set values on items in combobox, but everytime I try so I get the result 'null'. Am I defining the value wrong or am I trying to get the value in a wrong way?
// Setting the value
sqlCmd.CommandText = "SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0";
conn.Open();
using (var reader = sqlCmd.ExecuteReader())
{
while (reader.Read())
{
cmbUnajmljivaci.Items.Add(new { Id = reader["Id"].ToString(), Ime = reader["Ime"].ToString() });
}
cmbUnajmljivaci.ValueMember = "Id"; // <---
cmbUnajmljivaci.DisplayMember = "Ime";
}
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(cmbUnajmljivaci.SelectedValue));
using (SqlConnection sqlConn = new SqlConnection("CONNECTION STRING"))
{
DataSet ds = new DataSet();
SqlCommand sqlCmd = sqlConn.CreateCommand();
sqlConn.Open();
SqlDataAdapter SQA_DataAdapter = new SqlDataAdapter(sqlCmd);
SQA_DataAdapter.SelectCommand = new SqlCommand("SELECT Id, Ime FROM Unajmljivaci WHERE Aktivan = 0", sqlConn);
SQA_DataAdapter.Fill(ds, "Table");
if (ds != null)
if (ds .Tables.Count > 0)
{
cmbUnajmljivaci.ValueMember = "Id";
cmbUnajmljivaci.DisplayMember = "Ime";
cmbUnajmljivaci.DataSource = ds.Tables[0];
}
sqlConn.Close();
}
You need to set the data source of the combobox.
Try getting the Value like this:
dynamic dyn = cmbUnajmljivaci.SelectedItem;
string s = dyn.Id;
Or even inline like this:
//Retrieving the value
sqlCmd.Parameters.AddWithValue("#SifraUnajmljivca", Convert.ToString(((dynamic)cmbUnajmljivaci.SelectedItem).Id);
Sample Code for Reference to your problem,
DataSet ds = new DataSet();
DataTable dt = ds.Tables.Add();
dt.Columns.Add("ID");
dt.Columns.Add("Name");
dt.Rows.Add("0", "Item1");
dt.Rows.Add("1", "Item2");
For inserting the item with specified index you need to use the below code
//Insert the item into the collection with specified index
foreach (DataRow row in dt.Rows)
{
int id = Convert.ToInt32(row["ID"]);
string name=row["Name"].ToString();
comboBox1.Items.Insert(id,name);
}
Always index should start from 0 (Zero).
Easy way to add values to combobox
comboBox1.DataSource=dt;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "ID";
I have a result set of dataset like below
[![Dataset][1]][1]
Now I want to add the IF condition for checking like below
if(dataset rows(Usermail) == 10000){then go ahead}
this is my code.
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"].ToString()))
{
SqlCommand sqlComm = new SqlCommand("GET_INWARD_REMINDER_REPORT", conn);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
if(DataSet rowchecking)
{
}
}
So my issue, how to check and compare dataset columns.
You can do it like below:
int First = Convert.ToInt32(ds.Tables[0].Rows[0]["columnName1"].ToString());
string Second = ds.Tables[0].Rows[0]["columnName2"].ToString();
So for your case it can be like:
foreach (DataRow dr in ds.Tables[0].Rows)
{
if(dr["UserEmail"].ToString() == "10000")
{
//do something;
}
}
You can use a foreach to loop the rows and use DataRow.Field to get the email:
foreach(DataRow row in ds.Tables[0].Rows)
{
if(row.Field<string>("UserEmail") == "10000")
continue; // or revert it and do something if UserEmail != "1000"
}
After Fill dataset.
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if(ds.Tables[0].Rows[i]["UserEmail"].ToString() == "10000")
{
//do something;
}
}
}
I have a DataTable and I want to select multiple columns on the DataTable that matches the input in the textbox. The code below only selects 1 column.
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select data.Field<string> ("Description");
foreach (var res in result) {
txtxDescription.Text = res.ToString ();
}
How can I select 2 or more columns on DataTable using LINQ?
why not select full rows (DataRow object) and then take all necessary values from them?
var rows = mDataTable.AsEnumerable()
.Where(data => data.Field<string>("Code") == txtCode.Text);
foreach(DataRow r in rows)
{
txtxDescription.Text = r.Field<string>("Description");
}
another option is to project data to anonymous objects:
var result = from data in mDataTable.AsEnumerable ()
where data.Field<string>("Code") == txtCode.Text
select new
{
Description = data.Field<string> ("Description"),
Code = data.Field<string> ("Code")
};
foreach (var res in result)
{
// last value always replace `txtxDescription.Text` ??
txtxDescription.Text = res.Description;
txtxCode.Text = res.Code;
}
public void GridviewBinding()
{
DataSet ds = new DataSet();
string constr = ConfigurationManager.ConnectionStrings["SQLMSDB"].ConnectionString;
string sql = "select * from tbl_users";
using (SqlConnection conn = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sql))
{
cmd.Connection = conn;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(ds);
gridviewcontrol.DataSource = ds;
gridviewcontrol.DataBind();
ViewState["GridViewBindingData"] = ds.Tables[0];
}
}
}
}
protected void btn_searching_Click(object sender, EventArgs e)
{
if (!String.IsNullOrEmpty(txt_search.Text.Trim().ToString()) || !String.IsNullOrWhiteSpace(txt_search.Text.Trim().ToString()))
{
DataTable dt = (DataTable)ViewState["GridViewBindingData"];
var dataRow = dt.AsEnumerable().Where(x => x.Field<dynamic>("UserName") == txt_search.Text);
DataTable dt2 = dataRow.CopyToDataTable<DataRow>();
gridviewcontrol.DataSource = dt2;
gridviewcontrol.DataBind();
}
else
{
GridviewBinding();
}
}
I have the following code snippet:
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
DataRow dr = dt.Rows[0];
if (dt.Rows.Count > 0)
{
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
But I'm getting an error as:
There is no row at position 0.
I have the same query in sql server, but my table has contents for this query.
You are not loading data in to the DataSet. You have to call SqlDataAdapter.Fill to load the data in the DataSet. Also assign the row in the condition where you check that Rows count is greater then zero for not getting exception when not row exists.
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
adap.Fill(ds);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}
}
Please check your updated code below
if (!IsPostBack)
{
if (Request.QueryString["id"] != null)
{
string catid = Request.QueryString["id"].ToString();
Query1 = "select senderfirstname from messages where senderid='" + catid + "'";
adap = new SqlDataAdapter(Query1, con);
DataTable dt = ds.Tables["messages"];
if (dt.Rows.Count > 0)
{
DataRow dr = dt.Rows[0];
Session["table"] = dr["senderfirstname"].ToString();
}
else
{
Label1.Text = "error";
}
}