private void BrokerWiseSalesReport_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = null;
dataGridView1.Rows.Clear();
ds = GetBrokerDetailspageload();
//int ii = 0;
if (ds.Tables[0].Rows.Count != 0)
{
dataGridView1.DataSource = ds.Tables[0];
}
}
In Dataset[ if (ds.Tables[0].Rows.Count != 0)] I am getting the No of rows but
while storing in gridview using the statement
dataGridView1.DataSource = ds.Tables[0];
i am Getting no of rows as null
I am using c# connecting with Mysql
Only thing is m Not able to store the data in gridview from dataset
The which m using to store the data set data to gridview is right?
just guide me
dataGridView1.DataSource = ds.Tables[0];
You need to use MySqlDataAdapter.
private void BrokerWiseSalesReport_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = null;
dataGridView1.Rows.Clear();
ds = GetBrokerDetailspageload();
MySqlDataAdapter msd= new MySqlDataAdapter();
msd.Fill(ds);
//int ii = 0;
//if (ds.Tables[0].Rows.Count != 0)
// {
dataGridView1.DataSource = ds;
// }
}
Please let me know the further issues.
Update
public DataSet GetBrokerDetailspageload()
{
MySqlConnection mycon=new MySqlConnection("Your connection string");
string str = "SELECT sm.BrokerName,st.ID,sm.SalesCode,sm.BillNo,sm.SalesBy,st.ProductName,st.Quantity,st.SalesRate,st.NetWeight,st.Expense,st.Amount,st.VatP,St.VatAmt FROM salesmaster sm INNER JOIN salestransaction st ON sm.SalesCode=st.SalesCode";
MySqlCommand cmd=new MySqlCommand(str,mycon);
DataSet ds=new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
return ds;
}
private void BrokerWiseSalesReport_Load()
{
DataSet ds = new DataSet();
ds = null;
ds=GetBrokerDetailspageload();
dataGridView1.DataSource = ds.Tables[0];
}
I think you are missing one line of code.
Add this line after dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
Related
How to use loop to read all records by one click on the button. I have to print many reports.For each row in the table I need to create a report. And read until the last row of the table . My idea is using loop or index table but i don't know how to do it. This is my code:
private void btnin_Click(object sender, RoutedEventArgs e)
{
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" SELECT * FROM viewdata1 WHERE Customers = '" + cbbcustomer.Text + "'", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
cnn.Close();
XtraReport1 report = new XtraReport1();
report.DataSource = dt;
report.ShowPreviewDialog();
}
catch ( Exception ex )
{
MessageBox.Show(ex.Message);
}
}
You could iterate through the Datatable
foreach(DataRow row in dt.Rows)
{
DataTable dtrow = new DataTable();
dtrow = dt.Clone();
dtrow.ImportRow(row);
XtraReport1 report = new XtraReport1();
report.DataSource = dtrow;
//report.ShowPreviewDialog(); Not sure what happens here but maybe a print method is better suited?
}
Basically for each row you create a datatable with the same structure and import one row. Then its assigned as your datasource. This will iterate through all rows.
For some reasons, I had to change something in my code. I used Mark Vance's code but it didn't work:
DataTable a = new DataTable();
a = ((DataView)ctrlgridviewdulieu0.ItemsSource).ToTable();
foreach (DataRow row in a.Rows)
{
DataTable dtrow = new DataTable();
dtrow = a.Clone();
dtrow.ImportRow(row);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand(" SELECT * FROM viewdulieu2 WHERE Khachdat = N'" + dtrow.ToString() + "'", cnn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt1 = new DataTable();
da.Fill(dt1);
XtraReport1 report = new XtraReport1();
report.DataSource = dt1;
// report.Print();
cnn.Close();
report.ShowPreviewDialog();
}
catch (Exception ex)
{
cnn.Close();
MessageBox.Show(ex.Message);
}
}
I tried the following way, the data set is coming and table is binding.
But data is not inserting to the assigned drop down list in the gridview while Row Editing event
protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView2.EditIndex = e.NewEditIndex;
int index = e.NewEditIndex;
DropDownList ddl = (DropDownList)GridView2.Rows[index].FindControl("Receipttypeddl");
if (ddl != null)
{
DataSet ds = new DataSet();
SqlDataAdapter da;
con.Open();
string qry;
qry = "select * from ReceiptType";
SqlCommand cmd = new SqlCommand(qry);
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
ddl.DataSource = ds;
ddl.DataTextField = "Receiptmode";
ddl.DataValueField = "Receiptmode";
ddl.DataBind();
ListItem i = new ListItem("", "");//Data is not inserting into ddl
ddl.Items.Insert(0, i);
}
DataTable dts = new DataTable();
dts = (DataTable)ViewState["Receiptdetails"];
GridView2.DataSource = dts;
GridView2.DataBind();
}
you need bind dropdown on RowDataBound.
there seems to be no need to go to dB for each item.
protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView2.EditIndex = e.NewEditIndex;
BindGridView();
}
private void BindGridView()
{
DataTable dts = new DataTable();
dts = (DataTable)ViewState["Receiptdetails"];
GridView2.DataSource = dts;
GridView2.DataBind();
}
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddl = (DropDownList)e.Row.FindControl("Receipttypeddl");
BindDropdown(ddl);
}
}
DataTable ds = new DataTable();
private void BindDropdown(DropDownList ddl)
{
if (ds.Rows.Count == 0)
{
SqlDataAdapter da;
con.Open();
string qry;
qry = "select * from ReceiptType";
SqlCommand cmd = new SqlCommand(qry);
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
ddl.DataSource = ds;
ddl.DataTextField = "Receiptmode";
ddl.DataValueField = "Receiptmode";
ddl.DataBind();
ListItem i = new ListItem("", "");//Data is not inserting into ddl
ddl.Items.Insert(0, i);
}
Dal code
public DataSet selectlogin(string u_name, string u_password, string u_email, string action)
{
SqlConnection con = new SqlConnection(h);
SqlCommand cmd = new SqlCommand("", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "sp_login";
cmd.Parameters.AddWithValue("#name", u_name);
cmd.Parameters.AddWithValue("#email", u_email);
cmd.Parameters.AddWithValue("#password", u_password);
cmd.Parameters.AddWithValue("#action", action);
con.Open();
cmd.ExecuteNonQuery();
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
ad.Fill(ds);
return ds;
con.Close();
}
Bal code
public DataSet selectlogin(string u_name, string u_password, string u_email, string action)
{
DataSet ds = new DataSet();
ds = obj.selectlogin(u_name, u_password, u_email, action);
return ds;
}
CS code
protected void Btn_log(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = obj.selectlogin("", TextBox1.Text, TextBox2.Text,"login");
if (ds.Tables[0].Rows.Count > 0)
{
Response.Redirect("dashboard.aspx");
}
}
Stored procedure
if(#action='login')
select * from login where u_email=#email and u_pass=#password
The trouble might be here:
if (ds.Tables[0].Rows.Count > 0)
First check if the table with the index of 0 exists, then try to access the properties...
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0 )
This should help. Or at least it'll tell you that the returned dataset is empty (has no tables inside).
Try this
protected void Btn_log(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = obj.selectlogin("", TextBox1.Text, TextBox2.Text,"login");
bool hasRows = ds.Tables.Cast<DataTable>()
.Any(table => table.Rows.Count != 0);
if (hasRows)
{
Response.Redirect("dashboard.aspx");
}
}
Or try it( use != operator instead of > operator)
if (ds.Tables[0].Rows.Count **!=** 0)
{
Response.Redirect("dashboard.aspx");
}
CS code
protected void Btn_log(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds = obj.selectlogin("", TextBox1.Text, TextBox2.Text,"login");
if (ds!=null && ds.Tables[0].Count > 0 && ds.Tables[0].Rows.Count > 0)
{
Response.Redirect("dashboard.aspx");
}
}
I am using a grid to be bounded through code whose columns are defined at design time.
My code for binding the grid in the form_load() is :
private void SearchForm_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
try
{
cn = db.createConnection();
if (cn.State == System.Data.ConnectionState.Open)
cn.Close();
cn.Open();
cmd = new OleDbCommand("Select BillNo,PartyName,City,State,FORMAT(BillDt,'dd-mm-yyyy')as BillDt from BillMaster", cn);
da = new OleDbDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds);
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = ds.Tables[0];
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[0].Value = ds.Tables[0].Rows[i]["BillNo"].ToString();
dataGridView1.Rows[i].Cells[1].Value = ds.Tables[0].Rows[i]["PartyName"].ToString();
dataGridView1.Rows[i].Cells[2].Value = ds.Tables[0].Rows[i]["City"].ToString();
dataGridView1.Rows[i].Cells[3].Value = ds.Tables[0].Rows[i]["State"].ToString();
dataGridView1.Rows[i].Cells[4].Value = ds.Tables[0].Rows[i]["BillDt"].ToString();
}
ds.Dispose();
cmd.Dispose();
da.Dispose();
cn.Close();
}
I debugged the program and the data is assigned to the each field that is observed from the Immediate Window while debugging but when the form is displayed the data does not appear. And number of blank row as fetched from the dataset are created.
How do I solve this? Please help.
Try this:
dataGridView1.DataSource = ds; // dataset
dataGridView1.DataMember = "TableName";//TableName
Hope it will work.
I have a problem with stored procedures.
This code works (with a ListBox)
private void button4_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
string sqlCmd = "Drie duurste producten";
SqlCommand cmd = new SqlCommand(sqlCmd, connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = sqlCmd;
connection.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
listBox1.Items.Add(reader.GetValue(0).ToString());
}
}
connection.Close();
}
But how can I add this data to a DataGridView instead of a ListBox?
Thank you!
Change to
......
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
DataTable dt = new DataTable();
adapter.SelectCommand = cmd; {
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
......
usually a DataGridView is filled binding a complete datasource to its DataSource property and letting the control to figure out how to configure its columns and the formatting of the values displayed
SqlDataAdapter is the simplest way to do it.
But it is also possible to create DataTable and populate it manually and assign DataSource value of DataGridView to DataTable instance:
...
DataTable dt = new DataTable("test");
dt.Columns.Add("test");
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
DataRow dr = dt.NewRow();
dr[0] = reader.GetValue(0).ToString();
dt.Rows.Add(dr);
}
}
dataGridView1.DataSource = dt;
....
static public long Insert(BillAO ao)
{
try
{
SqlParameter[] Params =
{
new SqlParameter("#Status",ao.Status)
, new SqlParameter("#BAID",ao.BAID)
, new SqlParameter("#PhieuKhamID",ao.PhieuKhamID)
, new SqlParameter("#ThuNganID",ao.ThuNganID)
, new SqlParameter("#Ngay",ao.Ngay)
, new SqlParameter("#SoTien",ao.SoTien)
, new SqlParameter("#LyDo",ao.LyDo)
, new SqlParameter("#GhiChu",ao.GhiChu)
, new SqlParameter("#CreatedBy",ao.CreatedBy)
, new SqlParameter("#CreatedTime",ao.CreatedTime)
, new SqlParameter("#LastModifiedBy",ao.LastModifiedBy)
, new SqlParameter("#LastModifiedTime",ao.LastModifiedTime)
};
int result = int.Parse(SqlHelper.ExecuteScalar(HYPO.Utils.Config.ConnString, CommandType.StoredProcedure, "SP_Bill_Insert", Params).ToString());
return result;
}
catch (Exception ex)
{
if (ex.Message.Contains("duplicate"))
{
return -2;
}
return -1;
}
}
You need to use SqlDataAdapter to get the result of stored procedure in data table.
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
dataGridView1.DataSource = dt;
you don't need a CommandReader for this, all you have to do is to use DataAdapter and DataSet. and bind the dataset into your DataGridView
DataSet ds = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
You can do it with DataTable Or DataSet To Fill Data.... Here i did with DataTable....
Datatable data = new Datatable();
using (SqlDataAdapter adp = new SqlDataAdapter())
{
adp.SelectCommand = cmd;
adp.Fill(data);
GridView1.DataSorce = data;
GridView1.DataBind(); <--- Needed to bind GridView at a time While Filling DataTable data
}
You Can Also Check If DataTable Contains Data Or Not By This Way Before assigning DataTable to Gridview1.......
if(data.Rows.Counnt > 0)
{
GridView1.DataSorce = data;
GridView1.DataBind();
}
public void whateverToolStripMenuItem_Click(object sender, EventArgs e) {
// A previously declared and instantiated OpenFileDialog, i put it from Design Mode, but you can just
// declare it as
OpenFileDialog dlgImport = new OpenFileDialog();
//We show the dialog:
dlgImport.ShowDialog();
// We declare a variable to store the file path and name:
string fileName = dlgImport.FileName;
try {
// We invoke our method, wich is created in the following section, and pass it two parameters
// The file name and .... a DataGridView name that we put is the Form, so we can also see what
// We imported. Cool, isn't it?
importExcel(fileName, gridMain);
}
// It is best to always try to handle errors, you will se later why it is OleDbException and not
catch (OleDbException ex) {
MessageBox.Show("Error ocurred: " + ex.Message);
}
}