Skip to content

Commit 386ca7f

Browse files
vkuttypCopilot
andcommitted
feat: add SqlRow.AddToDataTable() and SqlRow.ToDataRow() extensions
Allows converting individual SqlRow instances to DataRow during QueryStreamAsync iteration for incremental DataGridView binding. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent d12d920 commit 386ca7f

1 file changed

Lines changed: 62 additions & 0 deletions

File tree

src/SqlDotnetty.Core/ISqlDatabase.cs

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,3 +123,65 @@ public static async Task<SqlValue> ScalarAsync(
123123

124124
private static object SqlValueToClr(SqlValue v) => v.ToClrObject();
125125
}
126+
127+
/// <summary>Extension helpers that convert <see cref="SqlRow"/> to ADO.NET <see cref="System.Data.DataRow"/>.</summary>
128+
public static class SqlRowExtensions
129+
{
130+
/// <summary>
131+
/// Converts this <see cref="SqlRow"/> to a <see cref="System.Data.DataRow"/> and adds it to
132+
/// <paramref name="table"/>. Columns are added to the table automatically on the first call
133+
/// if the table has no columns yet.
134+
/// </summary>
135+
/// <example>
136+
/// <code>
137+
/// var dt = new DataTable("Orders");
138+
/// await foreach (var row in conn.QueryStreamAsync("SELECT * FROM Orders"))
139+
/// {
140+
/// row.AddToDataTable(dt);
141+
/// // update UI incrementally here
142+
/// }
143+
/// dataGridView1.DataSource = dt;
144+
/// </code>
145+
/// </example>
146+
public static System.Data.DataRow AddToDataTable(this SqlRow row, System.Data.DataTable table)
147+
{
148+
if (table.Columns.Count == 0)
149+
{
150+
foreach (var col in row.Columns)
151+
table.Columns.Add(col.Name, typeof(object));
152+
}
153+
154+
var dataRow = table.NewRow();
155+
for (int i = 0; i < row.ColumnCount; i++)
156+
dataRow[i] = row[i].ToClrObject();
157+
table.Rows.Add(dataRow);
158+
return dataRow;
159+
}
160+
161+
/// <summary>
162+
/// Converts this <see cref="SqlRow"/> to a standalone <see cref="System.Data.DataRow"/>
163+
/// belonging to a new <see cref="System.Data.DataTable"/> (not yet added to any table).
164+
/// Useful when you need the <c>DataRow</c> without a pre-existing <c>DataTable</c>.
165+
/// </summary>
166+
/// <example>
167+
/// <code>
168+
/// await foreach (var row in conn.QueryStreamAsync("SELECT * FROM Orders"))
169+
/// {
170+
/// var dataRow = row.ToDataRow();
171+
/// // dataRow.Table holds the schema, dataRow[0] etc. hold CLR values
172+
/// }
173+
/// </code>
174+
/// </example>
175+
public static System.Data.DataRow ToDataRow(this SqlRow row)
176+
{
177+
var dt = new System.Data.DataTable();
178+
foreach (var col in row.Columns)
179+
dt.Columns.Add(col.Name, typeof(object));
180+
181+
var dataRow = dt.NewRow();
182+
for (int i = 0; i < row.ColumnCount; i++)
183+
dataRow[i] = row[i].ToClrObject();
184+
dt.Rows.Add(dataRow);
185+
return dataRow;
186+
}
187+
}

0 commit comments

Comments
 (0)